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

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