gpt4 book ai didi

java - 流 :Collect with supplier and accumulator

转载 作者:行者123 更新时间:2023-11-30 06:06:01 25 4
gpt4 key购买 nike

我一直在尝试使用 collect method of Stream , 将列表转换为 HashMap。我使用以下代码作为引用:

String result = list.parallelStream().collect(StringBuilder::new,
(response, element) -> response.append(" ").append(element),
(response1, response2) -> response1.append(",").append(response2.toString()))
.toString();

当我在 eclipse 中写下下面不完整的语句并在 ?

Map<String,Choice> map1=  list1.stream().collect(()-> new HashMap<String,Choice>(), 
(r,s) -> r.?,(r,s) -> r.putAll(s));

考虑到使用 StringBuilder 的代码片段,我的期望是,累加器函数的第一个参数应该是一个 HashMap,因为我使用 HashMap::new 作为供应商函数。按照这种理解,eclipse 应该建议我使用 HashMap 的方法,但事实并非如此。

但是,这似乎工作正常

list1.stream().collect(ArrayList::new, ArrayList::add, ArrayList::addAll);

已提及Java 8 Int Stream collect with StringBuilder但是,运气并不好。

最佳答案

如果您想更多地探索供应商、累加器、组合器,您应该在一开始就把它写得更清楚一些。

假设你有这样一个类:

static class Foo {
private final int id;

private final String s;

public Foo(int id, String s) {
super();
this.id = id;
this.s = s;
}

public int getId() {
return id;
}

public String getS() {
return s;
}

@Override
public String toString() {
return "" + id;
}
}

如果您知道在这种情况下s 是唯一的,您可以简单地这样做:

HashMap<String, Foo> result = Arrays.asList(new Foo(1, "a"), new Foo(2, "b"))
.stream()
.collect(HashMap::new,
(map, foo) -> map.put(foo.getS(), foo),
HashMap::putAll);

System.out.println(result); // {a=1, b=2}

但如果 s 不是唯一的,您可能需要收集到一个 List,这会使事情变得有点复杂:

 HashMap<String, List<Foo>> result = Arrays.asList(
new Foo(1, "a"),
new Foo(2, "b"),
new Foo(3, "a"))
.stream()
.parallel()
.collect(HashMap::new,
(map, foo) -> {
map.computeIfAbsent(foo.getS(), s -> new ArrayList<>()).add(foo);
},
(left, right) -> {
for (HashMap.Entry<String, List<Foo>> e : right.entrySet()) {
left.merge(
e.getKey(),
e.getValue(),
(l1, l2) -> {
l1.addAll(l2);
return l1;
});
}
});

System.out.println(result); // {a=[1, 3], b=[2]}

关于java - 流 :Collect with supplier and accumulator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45110964/

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