gpt4 book ai didi

Java-Stream-API : Map Reduce

转载 作者:行者123 更新时间:2023-11-30 10:08:10 26 4
gpt4 key购买 nike

假设我有多个类型为 obj_vx 的 java 对象,每个对象都有不同的日期时间(作为成员变量)。

obj_v1[D1]
obj_v1[D2]
obj_v1[D3]
obj_v1[D4]

obj_v2[D2]
obj_v2[D3]
obj_v2[D4]

obj_v3[D2]
obj_v3[D3]
obj_v3[D4]

obj_v4[D1]
obj_v4[D2]
obj_v4[D5]


obj_v5[D1]
obj_v5[D4]
obj_v5[D5]
obj_v5[D6]

obj_v5[D4]
obj_v5[D5]

or

obj_v1 [D1, D2, D3, D4]
obj_v2 [D2, D3, D4]
obj_v3 [D2, D3, D4]
obj_v4 [D1, D2, D5]
obj_v5 [D1, D4, D5, D6]
obj_v6 [D4, D5]

现在,我想针对给定日期D(D1 < D < D6) 筛选具有最年轻日期时间的obj_vx (D2 更年轻比 D1) 还旧(或等于)D。谁能告诉我如何使用 Java-Stream-API 构建它?

Map-Reduce 操作返回一个 obj_vx 对象列表。

响应:

- after 1st iteration
obj_v1 [D1, D2, D3]
obj_v2 [D2, D3]
obj_v3 [D2, D3]
obj_v4 [D1, D2]
obj_v5 [D1]
- after 2nd iteration
obj_v1[D3], obj_v2[D3], obj_v3[D3], obj_v4[D2], obj_v5[D1].

命题:

public class FilterTest {
static class X {
String group;
int y;

X(String group, int y) {
this.group = group;
this.y = y;
}

public String getGroup() {
return group;
}

public int getY() {
return y;
}

@Override
public String toString() {
return String.format("[group: '%s', y: '%s']", group, y);
}
}

public static void main(String[] args) {
int val = 2;

List<X> l = new ArrayList<>();
l.add(new X("A", 1));
l.add(new X("Y", 3));
l.add(new X("A", 2));
l.add(new X("Y", 1));
l.add(new X("B", 8));
l.add(new X("A", 3));

Map<String, X> map = l.stream().filter(d -> d.y <= val).collect(
Collectors.groupingBy(X::getGroup,
Collectors.collectingAndThen(
Collectors.reducing(
(X d1, X d2) -> d1.getY() > d2.getY() ? d1 : d2
),
Optional::get)));
System.out.println("m: " + map);
}
}

最佳答案

表达您的主张的更好方式可能是:

Map<String, X> map = l.stream()
.filter(d -> d.getY() <= val)
.collect(Collectors.toMap(X::getGroup, Function.identity(),
BinaryOperator.maxBy(Comparator.comparing(X::getY))));

关于Java-Stream-API : Map Reduce,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53866498/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com