需要在Java中索引流数据方面提供一些帮助。上下文是,我们需要手动为嵌入到其他文档中的文档设置索引(tldr;该方法中的输出需要为Stream )
return Stream.concat(firstStream, secondStream) <- these need to be indexed
.sorted(// sorted using Comparator)
.forEach? .map? // the class has index field with getter and setter so I think need to do `setIndex(i)` but wasnt sure where to get 'i'任何建议都将不胜感激!
发布于 2020-05-04 16:47:22
如果您可以从列表中自己构建流,则使用索引的IntStream而不是对象的Stream。
IntStream.range(0, firstList.size()).forEach(i -> firstList.get(i).setIndex(i));
int offsetForSecondList = firstList.size();
IntStream.range(0, secondList.size())
.forEach(i -> secondList.get(i).setIndex(offsetForSecondList + i));我没有尝试编译代码,所以请原谅任何错误。
否则,您的AtomicReference方法也会奏效。
发布于 2020-05-04 16:48:22
假设您有一个类MyObject:
class MyObject{
int index;
String name;
//getters,setters,cons, toString...
}如下所示可能是一个起点:
public static Stream<MyObject> fooBar(){
//just for example, inorder to get the streams to be concatnated
List<MyObject> first = List.of(new MyObject("foo"),new MyObject("foo"),new MyObject("foo"));
List<MyObject> second = List.of(new MyObject("bar"),new MyObject("bar"),new MyObject("bar"));
AtomicInteger ai = new AtomicInteger(0);
return Stream.concat(first.stream(), second.stream())
.peek(myo -> myo.setIndex(ai.getAndIncrement()));
}https://stackoverflow.com/questions/61596626
复制相似问题