Java Thread Filter Elements of a Specific Index

I am looking for a compressed way to filter items in a list by a specific index. My input example is as follows:

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 the elements at index 2 , 4 , 6 , 8 . I have a for loop that skips the elements matching the index, but I was hoping there would be an easy way to do this with threads. The final result will look like this:

 List<Double> filteredList = Arrays.asList(0.0, 1.0, 3.0, 5.0, 7.0, 9.0, 10.0); 
+7
java java-8 java-stream
source share
3 answers

You can create an IntStream to mimic the indices of the original list, and then remove those that are in the filteredIndexes list, and then match these indices with the corresponding element in the list (the best way is to have a HashSet<Integer> index for the indices, since they are unique in 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()); 
+14
source share

If your filteredIndexes list is pre-configured, you may not check each item this way:

 List<Double> filteredList = IntStream.rangeClosed(0, filterIndexes.size()) .mapToObj(idxPos -> idxPos == 0 ? originalList.subList(0, filterIndexes.get(idxPos)) : idxPos == filterIndexes.size() ? originalList.subList(filterIndexes.get(idxPos-1)+1, originalList.size()) : originalList.subList(filterIndexes.get(idxPos-1)+1, filterIndexes.get(idxPos))) .flatMap(List::stream) .collect(Collectors.toList()); 

Here we create a series of subscriptions that contain all the elements between the filtered indexes, and then simply smooth them into one final list. For large input (for example, a million numbers) this solution may be larger than the value suggested by @AlexisC.

+4
source share

If you sort the indexes in descending order , you can use java.util.List.remove(int) to remove the elements.

 List<Double> originalList = new ArrayList<>(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); filterIndexes.stream() // remove higher indixes first, because each remove affects all indexes to the right .sorted(Comparator.reverseOrder()) // make sure to use remove(int) not remove(Object) in java.util.List to use indexes .mapToInt(Integer::intValue) // remove each index .forEach(originalList::remove); // print results originalList.forEach(System.out::println); 
+2
source share

All Articles