Find value n steps away from target in List with stream
To build on top of Naman's answer:
- You can directly collect to a
List<String>
, which is more functional. - Also I would do the
.equals
test the other way in case one of the element of the list isnull
Here you go:
List<String> listTwo = IntStream.range(1, listOne.size())
.filter(i -> "test".equals(listOne.get(i))) // stream of indexes of "test" elements
.mapToObj(i -> listOne.get(i-1)) // stream of elements at the index below
.collect(Collectors.toList());
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));