ljacqu / JavaCollectionBehavior

Test cases to document different Java collections and their differences
0 stars 0 forks source link

Java collection behavior

Showcases the behavior of various List, Set and Map implementations and their differences.

Some highlights are given in this readme. Refer to the unit tests for all the details.

Difference between Collectors#toList, Collectors#toUnmodifiableList and Stream#toList

Consider the following blocks:

List<Integer> list1 = Stream.of(1, 2, 3)
  .collect(Collectors.toList()); // Since Java 8
List<Integer> list2 = Stream.of(1, 2, 3)
  .collect(Collectors.toUnmodifiableList()); // Since Java 10
List<Integer> list3 = Stream.of(1, 2, 3)
  .toList(); // Since Java 16

Is there any difference?

Difference between Collections#unmodifiableSet, Set#copyOf and Guava's ImmutableSet#copyOf

Set<Integer> origin = new LinkedHashSet<>(Arrays.asList(1, 2, 3));

Set<Integer> set1 = Collections.unmodifiableSet(origin);
Set<Integer> set2 = Set.copyOf(origin);
Set<Integer> set3 = ImmutableSet.copyOf(origin);