-1

I'm seeing an interesting behavior in stream processing of String arrays.

I'm doing something like this

String s =  "1_2_string";
String[] arr = s.split("_");
final Set<String> CAST_PATTERN = Set.of("string", "string2");
Arrays.stream(arr)
        .filter(id -> !CAST_PATTERN.contains(id))
        .map(Long::valueOf)
        .collect(Collectors.toSet());

Expected outcome should be a set [1,2] but actual outcome is [2,1] Collectors.toSet() creates an HashSet and not a SortedSet, so it should not mess up the order of data. Not sure why!!

Michael
  • 41,989
  • 11
  • 82
  • 128
  • I think, the 'order' in a hashset is somewhat indetermined or depends on the actual hashcode of each value. – T.M. Feb 22 '19 at 12:03
  • 4
    The order in an unordered set "should be" whatever it happens to come out as. They have no guaranteed order. – khelwood Feb 22 '19 at 12:04

1 Answers1

2

Normally, a Set does not have any guarantees about iteration order.

If you need a defined order, you can use Collectors.toCollection(TreeSet::new) (for natural order of elements) or Collectors.toCollection(LinkedHashSet::new) (for insertion order).

Thilo
  • 257,207
  • 101
  • 511
  • 656