Java ArrayList.removeAll (), but for indexes

Is there a way to do something like this:

ArrayList<String>.removeAll(ArrayList<Integer>)

C ArrayList<Integer>will be the indexes that I want to delete. I know that I could iterate over the list of indexes and use remove(index), but I was wondering if there was a way with one command to do this.

I know how to put this iteration on one line, my question is whether there is a way implemented by oracle.

+4
source share
2 answers

You can use Streamto iterate over indices for deletion. However, first take care to remove the highest index to avoid shifting other elements to remove from position.

public void removeIndices(List<String> strings, List<Integer> indices)
{
     indices.stream()
         .sorted(Comparator.reverseOrder())
         .forEach(strings::remove);
}

String , remove(int). List<Integer>, remove(E), .mapToInt(Integer::intValue) forEach.

+5

Java 8.

:

IntStream.of(7,6,5,2,1).forEach(i->list.remove(i));

List<Integer>, :

indexList.stream().mapToInt(Integer::intValue).forEach(i->list.remove(i));

, IntStream, Stream<Integer>, Stream<Integer> , , , List<Integer>, remove(Integer) , Integer, Integer.

+2

Source: https://habr.com/ru/post/1694873/


All Articles