Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert the values of a Map of List to a single List

How is the best (efficient and simple) way to convert the values of a Map<Object1, List<Object2>> to a List<Object2>. Should I simply iterate over all entries and adAll the items to a list?

like image 532
dinhokz Avatar asked Mar 30 '17 16:03

dinhokz


People also ask

How to convert a map to list in Java?

The Map class’s object contains key and value pairs. You can convert it into two list objects one which contains key values and the one which contains map values separately. To convert a map to list − Create a Map object. Create an ArrayList of integer type to hold the keys of the map. In its constructor call the method keySet () of the Map class.

What is the difference between a map and a list?

A Map is an object that maps keys to values or is a collection of attribute-value pairs. The list is an ordered collection of objects and the List can contain duplicate values. The Map has two values (a key and value), while a List only has one value (an element). So we can generate two lists as listed: List of keys from a Map.

Can a list be used as a key in a map?

We'll assume that each element of the List has an identifier that will be used as a key in the resulting Map. Learn several ways to convert a List into a Map using Custom Suppliers. Learn how to convert a List to a String using different techniques.

How to create a map from a list of Student objects?

Iterate through the items in the list and add each of them into the Map. Using Collectors.toMap () method: This method includes creation of a list of the student objects, and uses Collectors.toMap () to convert it into a Map. ide.geeksforgeeks.org , generate link and share the link here.


1 Answers

Here's a third way so you don't need to create an ArrayList, which is what you actually asked. This is the proper way to use streams because you're not changing the state of any object.

List<Object2> values = myMap.values()
                            .stream()
                            .flatMap(Collection::stream)
                            .collect(Collectors.toList());
like image 177
Nick Ziebert Avatar answered Oct 01 '22 02:10

Nick Ziebert