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?

5
  • What is the i'th value? Commented Nov 29, 2016 at 8: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? Commented Nov 29, 2016 at 8:10
  • 2
    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. Commented Nov 29, 2016 at 8:12
  • @AndyTurner I checked this link previously. But i don't want to use IntStream.range... Commented Nov 29, 2016 at 8: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. Commented Nov 29, 2016 at 8:37

2 Answers 2

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]
Sign up to request clarification or add additional context in comments.

3 Comments

Is there any alternate without using IntStream.range?
@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.
@KaranVerma u do know you can accept an answer if it actually helped you right?
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);

1 Comment

There is no need for extraneous braces. You can simply use mapToObj(i -> i + arr[i])

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.