toList preserves encounter order in its result, but toSet is documented to make no promise about iteration order, so only the size or membership should be relied on, not the order.
List<Integer> nums = List.of(1, 2, 3, 4, 5);
List<Integer> asList = nums.stream().collect(Collectors.toList());
System.out.println("toList preserves order: " + asList);
Set<Integer> asSet = nums.stream().collect(Collectors.toSet());
System.out.println("toSet size (order not guaranteed): " + asSet.size());
toList preserves order: [1, 2, 3, 4, 5]
toSet size (order not guaranteed): 5
Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.
Published 2026-09-27