Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java stream filter items of specific index

I'm looking for a concise way to filter out items in a List at a particular index. My example input looks like this:

List<Double> originalList = Arrays.asList(0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0);
List<Integer> filterIndexes = Arrays.asList(2, 4, 6, 8);

I want to filter out items at index 2, 4, 6, 8. I have a for loop that skips items that match the index but I was hoping there would be an easy way of doing it using streams. The final result would look like that:

List<Double> filteredList = Arrays.asList(0.0, 1.0, 3.0, 5.0, 7.0, 9.0, 10.0);
like image 989
Vedanth Avatar asked Mar 29 '16 20:03

Vedanth


People also ask

How do you filter a list of objects using a stream?

Java stream provides a method filter() to filter stream elements on the basis of given predicate. Suppose you want to get only even elements of your list then you can do this easily with the help of filter method. This method takes predicate as an argument and returns a stream of consisting of resulted elements.

Can we get index in stream?

Overview Though we cannot access the index of the stream directly, we have a few workarounds to iterate the Java stream forEach with index.

How do I get unique values from a stream?

distinct() returns a stream consisting of distinct elements in a stream. distinct() is the method of Stream interface. This method uses hashCode() and equals() methods to get distinct elements. In case of ordered streams, the selection of distinct elements is stable.


1 Answers

You can generate an IntStream to mimic the indices of the original list, then remove the ones that are in the filteredIndexes list and then map those indices to their corresponding element in the list (a better way would be to have a HashSet<Integer> for indices since they are unique by definition so that contains is a constant time operation).

List<Double> filteredList = 
    IntStream.range(0, originalList.size())
             .filter(i -> !filterIndexes.contains(i))
             .mapToObj(originalList::get)
             .collect(Collectors.toList());
like image 127
Alexis C. Avatar answered Sep 19 '22 05:09

Alexis C.