Files
javademos/java21-features/src/SequencedCollectionsDemo.java

30 lines
1.6 KiB
Java

import java.util.*;
/** JEP 431 (final): SequencedCollection, SequencedSet, SequencedMap. */
public class SequencedCollectionsDemo {
public static void main(String[] args) {
List<String> list = new ArrayList<>(List.of("a", "b", "c"));
System.out.println("getFirst/getLast: " + list.getFirst() + " " + list.getLast());
System.out.println("reversed view : " + list.reversed());
list.addFirst("z"); list.removeLast();
System.out.println("addFirst+removeLast: " + list);
LinkedHashSet<Integer> set = new LinkedHashSet<>(List.of(1, 2, 3));
System.out.println("LinkedHashSet reversed: " + set.reversed());
LinkedHashMap<String, Integer> map = new LinkedHashMap<>();
map.put("x", 1); map.put("y", 2); map.put("z", 3);
System.out.println("firstEntry/lastEntry : " + map.firstEntry() + " " + map.lastEntry());
map.putFirst("w", 0);
System.out.println("putFirst : " + map);
System.out.println("reversed map : " + map.reversed());
// reversed() is a view, not a copy
List<String> src = new ArrayList<>(List.of("1", "2")); List<String> rev = src.reversed(); src.add("3");
System.out.println("view sees add : " + rev);
try { List.of(1, 2).addFirst(0); } catch (UnsupportedOperationException e) { System.out.println("immutable list : UnsupportedOperationException"); }
try { new HashSet<>(List.of(1)).getClass().getMethod("getFirst"); } catch (NoSuchMethodException e) { System.out.println("HashSet : no getFirst (unordered)"); }
}
}