Java 8 lambdas 将列表分组到地图中

2022-01-22 00:00:00 java-8 java java-stream

我想取一个 List<Pojo>return 一个 Map<String, List 其中 Map的key是Pojo中的String值,我们称之为String key.

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:键:值:1

Pojo 1: Key:a value:1

Pojo 2:键:值:2

Pojo 2: Key:a value:2

Pojo 3:键:b 值:3

Pojo 3: Key:b value:3

Pojo 4:键:b 值:4

Pojo 4: Key:b value:4

我想要一个 Map<String, List<Pojo>>,其中 keySet() 大小为 2,其中键a"具有 Pojos 1 和 2,并且键"b" 有 pojos 3 和 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.

我怎样才能最好地使用 Java 8 lambdas 实现这一点?

How could I best achieve this using Java 8 lambdas?

推荐答案

看来简单的 groupingBy 变体就是你需要的:

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

Map<String, List<Pojo>> map = pojos.stream().collect(Collectors.groupingBy(Pojo::getKey));

相关文章