Streams: Collectors.toSet gives no ordering guarantee, unlike toList

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.

Code
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());
Output
toList preserves order: [1, 2, 3, 4, 5]
toSet size (order not guaranteed): 5
Advertisement
More in JAVA

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

© Java Coding Hub · About · Contact · Privacy · Terms