在使用列表分组地图时如何过滤年龄 [英] How to filter the age while grouping in map with list

查看:82
本文介绍了在使用列表分组地图时如何过滤年龄的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

类似于我之前的问题,此处我拥有的用户对象是这些

Similar to my previous question here, the User objects I have are these

new User("ayush","admin",23)
new User("ashish","guest",19) 
new User("ashish","admin",20) 
new User("garima","guest",29)
new User("garima","super",45)
new User("garima","guest",19)

现在,我正在尝试使这些用户的年龄趋势趋于不同.但是我需要过滤threshold岁以上的年龄.我可以使用

Now I am trying to get the name to varying ages trend for these users. But I need to filter them above a threshold age. I could get the trend using

Map<String, List<Integer>> userNameAndAgeTrend = users.stream().collect(Collectors.groupingBy(user-> user.getName(), Collectors.mapping(u-> u.getAge(), toList())));

这给了我{ashish=[19, 20], garima=[29, 45, 19], ayush=[23]}.但是在这种情况下,我无法使用阈值(例如 21年)正确过滤列表.有人可以帮忙吗?

this gives me {ashish=[19, 20], garima=[29, 45, 19], ayush=[23]}. But I am unable to filter the List properly using threshold for example 21 years in my situation using such grouping. Can someone please help?

此外,使用.filter(user -> user.getAge() > 21)不会给出ashish的映射,这也是我要存储的内容.我可以使用机器上安装的Java10并尝试建议的解决方案.

Also, using .filter(user -> user.getAge() > 21) gives no mapping for ashish, which is what I want to store too. I can use Java10 installed on my machine and trying the suggested solutions.

推荐答案

正如您在评论中确认的那样,这将为您提供输出

As confirmed by you in comments, this would give you as output

{garima=[29, 45], ayush=[23]}


明确指出了类似的行为(格式化我的行为):


Collectors.filtering

If you're looking for all the names, you could also use Collectors.filtering since java-9 which explicitly calls out a similar behavior (formatting mine) :

使用如上所示的 filtering 收集器将产生映射 从那个部门到一个空的Set .

Using a filtering collector as shown above would result in a mapping from that department to an empty Set.

如果流 filter() 操作 相反,该部门没有对应的映射 全部.

If a stream filter() operation were done instead, there would be no mapping for that department at all.

其用法应类似于:

Map<String, List<Integer>> userNameAndAgeTrend = users.stream()
        .collect(Collectors.groupingBy(User::getName, Collectors.mapping(User::getAge, 
                        Collectors.filtering(age -> age > 21, Collectors.toList()))));

现在的输出将是

{ashish=[], garima=[29, 45], ayush=[23]}

这篇关于在使用列表分组地图时如何过滤年龄的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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