0

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!

01000010
  • 64
  • 5
  • What do you mean by indexing? Simply number the elements from zero to n? Where do firstStream, and secondStream come from? Does their order also influence the indexing? Can you give a simple input example and the expected output? – Eritrean May 04 '20 at 16:30
  • so by indexing, i meant setting whatever is in firstStream and secondStream's `Integer index` field manually. The index field needs to be unique. I did try setting the index from where firstSteam and secondStream is using `AtomicReference` (for incrementing i within the method) from but wasn't sure if that's the right approach – 01000010 May 04 '20 at 16:39
  • 1
    [How to Iterate Over a Stream With Indices](https://www.baeldung.com/java-stream-indices) – Ole V.V. May 04 '20 at 16:52
  • 1
    Does this answer your question? [Is there a concise way to iterate over a stream with indices in Java 8?](https://stackoverflow.com/questions/18552005/is-there-a-concise-way-to-iterate-over-a-stream-with-indices-in-java-8) – Ole V.V. May 04 '20 at 16:54

2 Answers2

3

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.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
1

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()));
}
Eritrean
  • 15,851
  • 3
  • 22
  • 28