Collectors.toSet更改顺序

时间:2019-02-22 12:00:50

标签: java collections

我在String数组的流处理中看到了一个有趣的行为。

我正在做这样的事情

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 个答案:

答案 0 :(得分:1)

通常,Set不保证迭代顺序。

如果需要定义的顺序,则可以使用Collectors.toCollection(TreeSet::new)(用于元素的自然顺序)或Collectors.toCollection(LinkedHashSet::new)(用于插入顺序)。