3

How can I add the counter value to every nth item while iterating though a Stream?

Here is my simplest code:

Stream.of("a1","a2","a3")
    .map(x -> x + "counterValue")
    .findFirst()
    .ifPresent(System.out::println);

As I am adding "counterValue" string with every nth item, what I want to achieve is to add the ith value with every nth element.

The current program gives the output as a1counterValue.

I want the output as a10. 0 mean the index of that element.

Can anybody please help?

kukkuz
  • 41,512
  • 6
  • 59
  • 95
KayV
  • 12,987
  • 11
  • 98
  • 148
  • What is the i'th value? – marstran Nov 29 '16 at 08:10
  • 2
    At least for me it is not exactly clear, what you are trying to achieve. Can you give an example showing input and desired output? – stryba Nov 29 '16 at 08:10
  • 2
    http://stackoverflow.com/q/18552005/3788176 the easiest way is to iterate over a stream of indices, then you can count "every nth item". But it depends on the source of your stream as to whether you can refer to its element by index, or if you need to zip the two streams together. – Andy Turner Nov 29 '16 at 08:12
  • @AndyTurner I checked this link previously. But i don't want to use IntStream.range... – KayV Nov 29 '16 at 08:35
  • 1
    You need the index, so you will _need_ something like `Intstream.range` to track the index if you don't want to use a shared mutable value. – Nick Vanderhoven Nov 29 '16 at 08:37

2 Answers2

4

Is this what you are looking for?

 List<String> input = Arrays.asList("one", "two");
 IntStream.range(0, input.size())
      .mapToObj(i -> input.get(i) + i)
      .collect(Collectors.toList()) // [one0, two1]
Eugene
  • 117,005
  • 15
  • 201
  • 306
  • Is there any alternate without using IntStream.range? – KayV Nov 29 '16 at 08:35
  • 1
    @KaranVerma when you iterate internally over a Steam you are iterating over it's elements, not indexes. streams in general have no notion on indexes, so the answer is : no, no other way. – Eugene Nov 29 '16 at 08:37
  • @KaranVerma u do know you can accept an answer if it actually helped you right? – Eugene Nov 29 '16 at 18:17
0

You can iterate using index by using IntStream as shown below:

String[] arr = {"a1","a2","a3"};
int lentgh = arr.length;
IntStream.of(0, lentgh).
    mapToObj(((int i) -> i + arr[i])).findFirst().
     ifPresent(System.out::println);
Vasu
  • 21,832
  • 11
  • 51
  • 67