英文:
indexing <Stream> data Java
问题
需要一些关于在Java中索引流数据的帮助。背景是我们需要手动为嵌入到其他文档中的文档设置索引(简而言之,此方法的输出需要是一个流)。
return Stream.concat(firstStream, secondStream) // 这些需要被索引
.sorted(// 使用比较器排序)
.forEach? .map? // 该类具有带有getter和setter的索引字段,所以我认为需要执行 `setIndex(i)`,但不确定从哪里获取'i'
任何建议将不胜感激!
英文:
need some help with indexing Stream data in Java. The context is that we need to manually set index for document that is embedded to other document (tldr; the output needs to be Stream in this method)
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'
Any advice would be greatly appreciated!
答案1
得分: 3
如果您可以自己从列表构建流,请使用索引的 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
方法也可以工作。
英文:
If you can construct your streams yourself from lists, use IntStream
of indices rather than Stream
of objects.
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));
I have not tried to compile the code, so forgive any typo.
Otherwise your AtomicReference
approach works too.
答案2
得分: 1
假设您有一个名为MyObject的类:
class MyObject{
int index;
String name;
//getters,setters,cons, toString...
}
类似下面的内容可能是一个起始点:
public static Stream<MyObject> fooBar(){
//仅作示例,为了使流能够连接
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()));
}
英文:
Assuming you have a class MyObject:
class MyObject{
int index;
String name;
//getters,setters,cons, toString...
}
Something like below may be a starting point:
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()));
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论