Find value n steps away from target in List with stream

  • A+

Suppose I have a simple list:

List<String> listOne = Arrays.asList("str1", "result1", "test", "str4", "result2", "test", "str7", "str8"); 

The target is "test" and I want to add the value before the target into a new list, so the output would be [result1, result2].

It's easy enough to add the "test" values with something like listTwo = -> i.equals("test")).collect(Collectors.toList()); but how can I get the values elsewhere based on the location of the target ( in my example it's just the element before the target )

I tried just changing the i to i - 1 but that did nothing.

I am aware I can do it with a simple for loop, but just wondering how to apply the same logic with a stream.

for (int i = 1; i < listOne.size(); i++) {     if (listOne.get(i).equals("test")) {         listTwo.add(listOne.get(i - 1));     } } 


Something like

    IntStream.range(1, listOne.size())             .filter(i -> listOne.get(i).equals("test"))             .mapToObj(i -> listOne.get(i - 1))             .forEach(item -> listTwo.add(item)); 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: