java嵌套对象,java – 从嵌套流中收集一组对象
我有一個場景,我有兩個for循環,一個嵌套在另一個.在內部循環中,對于每次迭代,我都有創建特定類型的新實例所需的信息.我想將代碼從for循環更改為使用流,因此我可以將所有對象收集到ImmutableSet中.但是,我無法制作一個編譯和工作的版本.下面的示例程序說明了我最接近的嘗試.它編譯,但其中一個參數是硬編碼的.
如何修復下面的流,以便在分配Bar時,我有變量s和n可用?
class Bar {
private final String s;
private final Integer n;
Bar(String s, Integer n) {
this.s = s;
this.n = n;
}
}
public class Foo {
private static List getList(String s) {
return Lists.newArrayList(s.hashCode());
}
Foo() {
ImmutableSet set = ImmutableSet.of("foo", "bar", "baz")
.stream()
.flatMap(s -> getList(s).stream())
.map(n -> new Bar("", n)) // I need to use s here, not hard-code
.collect(ImmutableSet.toImmutableSet());
}
}
總結
以上是生活随笔為你收集整理的java嵌套对象,java – 从嵌套流中收集一组对象的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: php scrscriptipt,XSS
- 下一篇: SpringMVC响应使用案例(带数据页