Close

Java Collections - How to remove a range of elements from collections?

[Last Updated: Jun 11, 2018]

Java Collections Java 

Following utility methods shows how to remove elements by range from a Collection or Map.

package com.logicbig.example;

import java.util.*;

public class CollectionRemoveRange {

  public static void removeRange(List<?> list, int start, int end) {
      list.subList(start, end).clear();//list.sublist() returns a view
  }

  public static void removeRange(Collection<?> c, int start, int end) {
      if (c instanceof List) {
          removeRange((List) c, start, end);
          return;
      }

      ArrayList<?> list = new ArrayList<>(c);
      removeRange(list, start, end);
      c.retainAll(list);
  }

  public static void removeRange(Map<?, ?> map, int start, int end) {
      Set<?> keySet = map.keySet();//returns a view
      removeRange(keySet, start, end);
  }

  public static void main(String[] args) {
      List<Integer> list = List.of(1, 4, 12, 7, 9);

      System.out.println("-- List --");
      List<Integer> arrayList = new ArrayList<>(list);
      System.out.println("before: " + arrayList);
      removeRange(arrayList, 1, 3);
      System.out.println("after: " + arrayList);

      System.out.println("-- SortedSet --");
      SortedSet<Integer> treeSet = new TreeSet<>(list);
      System.out.println("before: " + treeSet);
      removeRange(treeSet, 1,3);
      System.out.println("after: " + treeSet);

      System.out.println("-- LinkedHashSet --");
      Set<Integer> linkedHashSet = new LinkedHashSet<>(list);
      System.out.println("before: " + linkedHashSet);
      removeRange(linkedHashSet, 1,3);
      System.out.println("after: " + linkedHashSet);

      Map<Integer,String> map = Map.of(1,"one", 4, "four", 2, "two",
              3, "three", 6, "six");

      System.out.println("-- SortedMap --");
      Map<Integer, ?> treeMap = new TreeMap<>(map);
      System.out.println("before: " + treeMap);
      removeRange(treeMap, 1,3);
      System.out.println("after: " + treeMap);

      System.out.println("-- LinkedHashMap --");
      Map<Integer, ?> linkedHashMap = new LinkedHashMap<>(map);
      System.out.println("before: " + linkedHashMap);
      removeRange(linkedHashMap, 1,3);
      System.out.println("after: " + linkedHashMap);
  }
}
-- List --
before: [1, 4, 12, 7, 9]
after: [1, 7, 9]
-- SortedSet --
before: [1, 4, 7, 9, 12]
after: [1, 9, 12]
-- LinkedHashSet --
before: [1, 4, 12, 7, 9]
after: [1, 7, 9]
-- SortedMap --
before: {1=one, 2=two, 3=three, 4=four, 6=six}
after: {1=one, 4=four, 6=six}
-- LinkedHashMap --
before: {3=three, 2=two, 1=one, 6=six, 4=four}
after: {3=three, 6=six, 4=four}

Since collections like HashSet and HashMap do not maintain any insertion or sorted order, removing elements by range will probably not make very much sense for them.

See Also