Newsletter |
How to Convert List to Map in Java 8
Core Java » on Oct 26, 2016 { 6 Comments } By Sivateja
If you have a scenario where you need to convert List of objects to a Map, prior to java 8 you can do this by writing a simple for loop which is iterative. But in this article I will show you how to convert List to Map using java 8 lambda expression.
Java 8 Convert List to Map Example
Lets a take pojo class named Account with properties accNo, accType, accStatus.
Account.java
public class Account { private int accNo; private String accType; private String accStatus; public Account(int accountNo, String accountType, String accountStatus){ accNo = accountNo; accType = accountType; accStatus = accountStatus; } public int getAccNo() { return accNo; } public void setAccNo(int accNo) { this.accNo = accNo; } public String getAccType() { return accType; } public void setAccType(String accType) { this.accType = accType; } public String getAccStatus() { return accStatus; } public void setAccStatus(String accStatus) { this.accStatus = accStatus; } }
ListtoMap.java
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class ListtoMap { public static void main(String[] args) { List<Account> li = new ArrayList<Account>(); Account ac1= new Account(100,"Savings","Open"); Account ac2= new Account(101,"Checking","Closed"); li.add(ac1); li.add(ac2); // Before Java 8 Map<Integer, String> beforeJava8 = new HashMap<>(); for (Account acc: li) { beforeJava8.put(acc.getAccNo(), acc.getAccStatus()); } System.out.println("Before Java 8 "+beforeJava8); // Java 8 Using Lambda expression and Stream API Map<Integer, String> map = li.stream().collect(Collectors.toMap(x -> x.getAccNo() , x -> x.getAccStatus())); System.out.println("Java 8 "+map); } }
Output
Before Java 8 {100=Open, 101=Closed}
Java 8 {100=Open, 101=Closed}
Hey its same output 😉 I just tried to show both ways [ with and without lambda expression ].
You Might Also Like
::. About the Author .:: | ||
Comments
6 Responses to “How to Convert List to Map in Java 8”
Nice artical Siva.
gr8 bro
nice updates in java8 please give me more details about this new features of java 8
How to work internally hashmap?
This is really very nice and useful example.
thanks
great explanation bro!!!