我在字符串數組的流處理中看到了一個有趣的行為。我正在做這樣的事情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());預期結果應該是一個集合 [1,2] 但實際結果是 [2,1] Collectors.toSet() 創建一個 HashSet 而不是一個 SortedSet,所以它不應該弄亂數據的順序。不知道為什么??!
1 回答

婷婷同學_
TA貢獻1844條經驗 獲得超8個贊
通常,Set 對迭代順序沒有任何保證。
如果需要定義順序,可以使用Collectors.toCollection(TreeSet::new)
(用于元素的自然順序)或Collectors.toCollection(LinkedHashSet::new)
(用于插入順序)。
添加回答
舉報
0/150
提交
取消