Java 8 lambdas 将列表分组到地图中 [英] Java 8 lambdas group list into map

查看:23
本文介绍了Java 8 lambdas 将列表分组到地图中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想取一个 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));

这篇关于Java 8 lambdas 将列表分组到地图中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆