Java.Collections.How to get a List with all elements except the first and last 3 in one call from List?

✅ One-liner using subList:

List<T> middle = list.subList(3, list.size() - 3);

🔍 Explanation:

  • list.subList(fromIndex, toIndex) returns a view of the list from fromIndex (inclusive) to toIndex (exclusive).
  • So:
    • 3 skips the first 3 elements,
    • list.size() - 3 excludes the last 3 elements.

💡 Example:

List<String> items = List.of("a", "b", "c", "d", "e", "f", "g", "h", "i");
List<String> middle = items.subList(3, items.size() - 3);

System.out.println(middle); // Output: [d, e, f]

⚠️ Caution:

  • Make sure the list has at least 6 elements, or this will throw IndexOutOfBoundsException.
  • If you want to return a new list, wrap it like this:
List<T> middleCopy = new ArrayList<>(list.subList(3, list.size() - 3));
This entry was posted in Без рубрики. Bookmark the permalink.