Java 8流比较两个对象并对它们运行一个函数 [英] Java 8 stream compare two objects and run a function on them

查看:454
本文介绍了Java 8流比较两个对象并对它们运行一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个流,我希望根据匹配的ID分割成更小的部分,然后在每个部分/元素上应用一些处理逻辑。

I've a a stream which I want to partition into smaller parts based on matching Id and then apply some proccessing logic on each of the part/element.

class BigRequest{
String bId;
List<Parts> parts;
//getters and setter here
}

Class Parts{
String pId;
String partId;
//getters and setter here
}

我想隔离和创建当不同部分的partId相同时,大小为10的部分列表。

I want to segregate and create a list of Parts of size 10 when the partId of different parts are same.

如何使用filter或reduce或groupingBy函数来比较这两个元素并将它们放到一个列表?
我试过过滤器,如下所示,不带p1变量:

How to use the filter or reduce or groupingBy function to compare the two elements and put them to a list? I've tried filter like below, doesn't take p1 variable:

big.stream().filter( p -> p.getPartId() == p1.getPartId()) //error

试过分组就像这样

big.stream().collect(Collectors.groupingBy(Parts::getPartId) //error

我想迭代过滤/缩减列表另一个并调用另一个名为abc()的函数。怎么能我是用Java Streams做的?

I want to iterate over the filtered/reduced list a another and call another function called abc(). How can I do it using Java Streams?

伪:

big.getParts().stream.
//dividing logic logic
for(i < parts.size)
    abc(p)

谢谢

推荐答案

您可以使用以下内容:

 Map<String,List<Parts>> commonId = big.getParts().
                stream().
                collect(
                        Collectors.groupingBy(
                            Parts::getPartId,
                            Collectors.mapping(
                                Function.identity(),
                                Collectors.toList()
                            )
                        )
                ); 

之后,您只需迭代地图并应用您的功能即可。
commonId.entrySet()。stream()。map(entry - > apply(entry))...

and after it, you will just need to iterate over the map and apply your function. commonId.entrySet().stream().map(entry -> apply(entry))...

更新
我们可以省略 Collectors.mapping(Function.identity(),Collectors.toList())部分,因为它是 groupingBy

Map<String,List<Parts>> commonId = big.getParts().
                    stream().
                    collect(
                            Collectors.groupingBy(
                                Parts::getPartId
                            )
                    ); 

这篇关于Java 8流比较两个对象并对它们运行一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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