Java stream map to map of lists

Java 8: How to Convert a Map to List

A Java Map implementation is an collection that maps keys to values. Every Map Entry contains key/value pairs, and every key is associated with exactly one value. The keys are unique, so no duplicates are possible.

A common implementation of the Map interface is a HashMap :

Map students = new HashMap<>(); students.put(132, "James"); students.put(256, "Amy"); students.put(115, "Young"); System.out.println("Print Map: " + students); 

We’ve created a simple map of students (Strings) and their respective IDs:

A Java List implementation is a collection that sequentially stores references to elements. Each element has an index and is uniquely identified by it:

List list = new ArrayList<>(Arrays.asList("James", "Amy", "Young")); System.out.println(list); System.out.println(String.format("Third element: %s", list.get(2)); 
[James, Amy, Young] Third element: Young 

The key difference is: Maps have two dimensions, while Lists have one dimension.

Though, this doesn’t stop us from converting Maps to Lists through several approaches. In this tutorial, we’ll take a look at how to convert a Java Map to a Java List:

Convert Map to List of Map.Entry

Java 8 introduced us to the Stream API — which were meant as a step towards integrating Functional Programming into Java to make laborious, bulky tasks more readable and simple. Streams work wonderfully with collections, and can aid us in converting a Map to a List.

Читайте также:  Форма ввода в HTML5

The easiest way to preserve the key-value mappings of a Map , while still converting it into a List would be to stream() the entries, which consist of the key-value pairs.

The entrySet() method returns a Set of Map.Entry elements, which can easily be converted into a List , given that they both implement Collection :

List> singleList = students.entrySet() .stream() .collect(Collectors.toList()); System.out.println("Single list: " + singleList); 
Single list: [256=Amy, 115=Young, 132=James] 

Since Streams are not collections themselves — they just stream data from a Collection — Collectors are used to collect the result of a Stream ‘s operations back into a Collection . One of the Collectors we can use is Collectors.toList() , which collects elements into a List .

Convert Map to List using Two Lists

Since Maps are two-dimensional collections, while Lists are one-dimensional collections — the other approach would be to convert a Map to two List s, one of which will contain the Map’s keys, while the other would contain the Map’s values.

Thankfully, we can easily access the keys and values of a map through the keySet() and values() methods.

The keySet() method returns a Set of all the keys, which is to be expected, since keys have to be unique. Due to the flexibility of Java Collections — we can create a List from a Set simply by passing a Set into a List ‘s constructor.

The values() method returns a Collection of the values in the map, and naturally, since a List implements Collection , the conversion is as easy as passing it in the List ‘s constructor:

List keyList = new ArrayList(students.keySet()); List valueList = new ArrayList(students.values()); System.out.println("Key List: " + keyList); System.out.println("Value List: " + valueList); 
Key List: [256, 115, 132] Value List: [Amy, Young, James] 

Convert Map to List with Collectors.toList() and Stream.map()

We’ll steam() the keys and values of a Map , and then collect() them into a List :

List keyList = students.keySet().stream().collect(Collectors.toList()); System.out.println("Key list: " + keyList); List valueList = students.values().stream().collect(Collectors.toList()); System.out.println("Value list: " + valueList); 

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

Key list: [256, 115, 132] Value list: [Amy, Young, James] 

This approach has the advantage of allowing us to perform various other operations or transformations on the data before collecting it. For example, knowing that we’re working with Strings — we could attach an anonymous function (Lambda Expression). For example, we could reverse the bytes of each Integer (key) and lowercase every String (value) before collecting them into a List :

List keyList = students.keySet() .stream() .map(Integer::reverseBytes) .collect(Collectors.toList()); System.out.println("Key list: " + keyList); List valueList = students.values() .stream() .map(String::toLowerCase) .collect(Collectors.toList()); System.out.println("Value list: " + valueList); 

Note: The map() method returns a new Stream in which the provided Lambda Expression is applied to each element. If you’d like to read more about the Stream.map() method, read our Java 8 — Stream.map() tutorial.

Running this code transforms each value in the streams before returning them as lists:

Key list: [65536, 1929379840, -2080374784] Value list: [amy, young, james] 

We can also use Collectors.toCollection() method, which allows us to chose the particular List implementation:

List keyList = students.keySet() .stream() .collect(Collectors.toCollection(ArrayList::new)); List valueList = students.values() .stream() .collect(Collectors.toCollection(ArrayList::new)); System.out.println("Key list: " + keyList); System.out.println("Value list: " + valueList); 
Key list: [256, 115, 132] Value list: [Amy, Young, James] 

Convert Map to List with Stream.filter() and Stream.sorted()

We’re not only limited to mapping values to their transformations with Stream s. We can also filter and sort collections, so that the lists we’re creating have certain picked elements. This is easily achieved through sorted() and filter() :

List sortedValueList = students.values() .stream() .sorted() .collect(Collectors.toList()); System.out.println("Sorted Values: " + sortedValueList); 

After we sorted the values we get the following result:

Sorted Values: [Amy, James, Young] 

We can also pass in a custom comparator to the sorted() method:

List sortedValueList = students.values() .stream() .filter(value-> value.startsWith("J")) .collect(Collectors.toList()); System.out.println("Sorted Values: " + sortedValueList); 

If you’d like to read more about the sorted() method and how to use it — we’ve got a guide on How to Sort a List with Stream.sorted().

Convert Map to List with Stream.flatMap()

The flatMap() is yet another Stream method, used to flatten a two-dimensional stream of a collection into a one-dimensional stream of a collection. While Stream.map() provides us with an A->B mapping, the Stream.flatMap() method provides us with a A -> Stream mapping, which is then flattened into a single Stream again.

If we have a two-dimensional Stream or a Stream of Streams, we can flatten it into a single one. This is conceptually very similar to what we’re trying to do — convert a 2D Collection into a 1D Collection. Let’s mix things up a bit by creating a Map where the keys are of type Integer while the values are of type List :

Map> newMap = new HashMap<>(); List firstName = new ArrayList(); firstName.add(0, "Jon"); firstName.add(1, "Johnson"); List secondName = new ArrayList(); secondName.add(0, "Peter"); secondName.add(1, "Malone"); // Insert elements into the Map newMap.put(1, firstName); newMap.put(2, secondName); List valueList = newMap.values() .stream() // Aforementioned A -> Stream mapping .flatMap(e -> e.stream()) .collect(Collectors.toList()); System.out.println(valueList); 

Conclusion

In this tutorial, we have seen how to convert Map to List in Java in several ways with or without using Java 8 stream API.

Источник

Java 8 stream map()

map() method in java 8 stream is used to convert an object of one type to an object of another type or to transform elements of a collection.
map() returns a stream which can be converted to an individual object or a collection, such as a list.

Typical applications of map() would be
1. Convert a list of object of one type to a list of objects of another type.
2. Convert a list of string in lower case to a list of upper case strings.
3. Create a list of numbers which are square or cube of numbers in another list etc.

Returns a stream consisting of the results of applying the given function to the elements of this stream.

map() is invoked for each element of the stream. It is an intermediate operation.

Signature of map() method is

where R and T are generic types

map() accepts an argument of type java.util.function.Function as argument.
Function is a functional interface with a single method apply() which takes a single argument and returns a value.

This means that we can supply a Lambda expression to map() which accepts a value and returns another value.

If you match the signatures of apply() and map() closely, then the return type of apply() is same as the return type of map() .
This means that the type of stream returned by map() is the same as the type of value returned by the lambda expression that is supplied to map() .

If this is not clear to you, don’t worry. The examples that follow will clarify the usage of map() .
Stream map() to convert list of objects
Let’s say we want to convert list of Subscriber objects to a list of User objects. Below are these two classes

public class Subscriber < private String sName; // getter and setter methods >public class User < private String uName; // getter and setter methods >

Below is an example of map() method for this conversion.

List users = subscribers.stream(). map(s -> < User u = new User(); u.setuName(s.getsName()); return u; >).collect(Collectors.toList());

Lambda expression supplied to map() is creates a new User object and populates its field with the corresponding field of Subscriber class.
Remember that map() will be called for each element of the stream.
map() will return a stream and to convert it to a list, use its collect() method with Collectors.toList() .

Stream map() to convert list of objects to list of string
Below is an example to convert a list of objects to a list of string.
For example, we might want the list of names of Subscribers from the list of Subscriber objects.

subscribers.stream(). map(s -> s.getSName()). collect(Collectors.toList());

Stream map() to convert string to integer
map() method can be used to convert a list of string to a list of integers and vice-versa. Following is an example to convert a list of string to a list of integers.

List str = List.of("1","2","3","4"); List nums = str.stream(). map(s -> Integer.parseInt(s)). collect(Collectors.toList());

This code can also be written using method reference as

List str = List.of("1","2","3","4"); List nums = str.stream(). map(Integer::parseInt). collect(Collectors.toList());

To convert a list of integers to a list of string values with map() , the code would be

List nums = List.of(1,2,3,4); List str = nums.stream(). map(String::valueOf). collect(Collectors.toList());

Stream map() to convert to upper case
Java 8 stream map() method can be used to convert a list of string to a corresponding list with elements in upper case. Example,

List lower = List.of("ab","cd","ef","gh"); List upper = lower.stream(). map(s -> s.toUpperCase(s)). collect(Collectors.toList());

With method reference, above code reduces to

lower.stream(). map(String::toUpperCase). collect(Collectors.toList());

Java 8 & above

  • Lambda expressions tutorial with examples
  • Stream tutorial with examples
  • static methods in interface
  • default methods in interface
  • Java 8 Optional with example
  • Java 8 LocalDate
  • Java 8 LocalTime
  • Java 8 LocalDateTime
  • Get last stream element
  • Predicate interface
  • IntPredicate interface
  • Supplier interface
  • Consumer interface
  • Java 8 stream filter with example
  • Java 8 stream map() method
  • Java 8 stream flatMap() example
  • Java 8 Stream.max() method
  • Java 8 Stream.min() method
  • Java 8 forEach loop
  • Modify a variable inside forEach loop and lambda expression
  • Convert list of objects to map java 8
  • StringJoiner class in java 8
  • Java 9 modules – Learning modularization
  • Java 9 cleaner example for garbage collection
  • Switch expressions in java 14
  • Java 16 records
  • Download and install OpenJDK 17
  • Sealed classes in java 17

Источник

Оцените статью