Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 lambdas group list into map

I want to take a List<Pojo> and return a Map<String, List<Pojo>> where the Map's key is a String value in Pojo, let's call it String key.

To clarify, given the following:

Pojo 1: Key:a value:1

Pojo 2: Key:a value:2

Pojo 3: Key:b value:3

Pojo 4: Key:b value:4

I want a Map<String, List<Pojo>> with keySet() sized 2, where key "a" has Pojos 1 and 2, and key "b" has pojos 3 and 4.

How could I best achieve this using Java 8 lambdas?

like image 663
Robert Bain Avatar asked Jun 10 '15 12:06

Robert Bain


People also ask

Can we convert list to map in Java?

With Java 8, you can convert a List to Map in one line using the stream() and Collectors. toMap() utility methods. The Collectors. toMap() method collects a stream as a Map and uses its arguments to decide what key/value to use.

How does Groupby work in Java 8?

In Java 8, you retrieve the stream from the list and use a Collector to group them in one line of code. It's as simple as passing the grouping condition to the collector and it is complete. By simply modifying the grouping condition, you can create multiple groups.


1 Answers

It seems that the simple groupingBy variant is what you need :

Map<String, List<Pojo>> map = pojos.stream().collect(Collectors.groupingBy(Pojo::getKey)); 
like image 93
Eran Avatar answered Sep 20 '22 01:09

Eran