Saturday 25 June 2016

Convert ArrayList to Map using Stream

Earlier(before java8), If we want to covert the List to Map, we to have write following statements.

List<String> list=new ArrayList<String>();
list.add("abc");
list.add("cde");
list.add("efg");
Map<String, String> map=HashMap<String,String>();
for(String value:list){
        map.put(value,value);
}

In Java 8 creating a Map is one line statement:

Map<String, String> map=list.stream().collect(Collectors.toMap(Function.identity(),Function.identity()));

Another Example

public class Test{
    private String key;
    public Test(String key){
         this.key=key
    }
    public String getKey(){
          return key;
    }
}

List<Test> list=new ArrayList<Test>();
list.add(new Test("abc"));
list.add(new Test("cde"));
list.add(new Test("efg"));

 Map<String, String> map=list.stream().collect(Collectors.toMap(Test::get , Function.identity()));
                                      OR
Map<String, String> map=list.stream().collect(Collectors.toMap(t->t.get() , Function.identity()));