Java 8 Convert Map to List using Streams API
7 years ago Lalit Bhagtani 0
Java 8 Convert Map to List :- In this tutorial, we will learn to convert map to list using Stream API.
Problem Statement :-
Given a map of Integer as a key and String as a Value convert it to the list, containing all the values of Map.
Let’s see the implementation of above problem in java 7 and in java 8.
Java 7 :- To implement this, iterate through the set of map’s Entry object and add it’s value to newly created List object.
public static void main(String[] args){ Map<Integer,String> map = new HashMap<Integer,String>(); map.put(1,"Robert"); map.put(2,"Martin"); map.put(3,"Jack"); List<String> list = new ArrayList<String>(); Set<Entry<Integer,String>> set = map.entrySet(); Iterator<Entry<Integer,String>> iterate = set.iterator(); while(iterate.hasNext()){ list.add(iterate.next().getValue()); } for(String s : list){ System.out.println(s); } }
Java 8 :- To implement this, we will use stream’s map() method.
public static void main(String[] args){ Map<Integer,String> map = new HashMap<Integer,String>(); map.put(1,"Robert"); map.put(2,"Martin"); map.put(3,"Jack"); List<String> list = map.entrySet().stream().map( v -> v.getValue()).collect(Collectors.toList()); list.forEach( v -> System.out.println(v)); }
Result :-
Robert
Martin
Jack
Reference :- Stream’s map() JavaDocs
That’s all for Java 8 Convert Map to List. If you liked it, please share your thoughts in comments section and share it with others too.