gpt4 book ai didi

java - Comparator 的等价恒等运算

转载 作者:行者123 更新时间:2023-11-30 07:39:55 25 4
gpt4 key购买 nike

是否存在可能存在的 Comparator 的身份表示?

在搜索Removing overloaded method in Java中简化代码,我考虑了这一点并最终得出结论,如果每次比较都导致对象相等,那么顺序不会真正改变,从而使操作成为同一性。因此,我最终得到了这样的(一个低效的)建议:

public static <T, G> List<G> toListOfNewType(List<T> inputList, Function<T, G> mapperFunction) {
return toListOfNewType(inputList, mapperFunction, (a, b) -> 0); // overloaded with comparator for 'G' type
}

但我现在想知道的是,这是否也适用于具有自定义 compareTo 实现的对象?鉴于 Stream 实现,假设这真的安全吗?

编辑:我尝试过并保留顺序的某些测试如下:

List<Integer> integers = List.of(1, 3, 45356, 47424, 34234, 4, 4, 234234, 234, 0, -23, -34);
System.out.println(integers);
System.out.println(integers.stream().sorted((a, b) -> 0).collect(Collectors.toList()));
System.out.println(integers.stream().sorted((a, b) -> 0).parallel().collect(Collectors.toList()));

[1, 3, 45356, 47424, 34234, 4, 4, 234234, 234, 0, -23, -34]
[1, 3, 45356, 47424, 34234, 4, 4, 234234, 234, 0, -23, -34]
[1, 3, 45356, 47424, 34234, 4, 4, 234234, 234, 0, -23, -34]

List<String> strings = List.of("aadad", "Z", "vsadasd", "zadad", "C", "Aadasd");
System.out.println(strings);
System.out.println(strings.stream().sorted((a, b) -> 0).collect(Collectors.toList()));
System.out.println(strings.stream().sorted((a, b) -> 0).parallel().collect(Collectors.toList()));

[aadad, Z, vsadasd, zadad, C, Aadasd]
[aadad, Z, vsadasd, zadad, C, Aadasd]
[aadad, Z, vsadasd, zadad, C, Aadasd]

Set<Integer> integerSet = Set.of(1, 3, 45356, 47424, 34234, 4, 234234, 234, 0, -23, -34);
System.out.println(integerSet);
System.out.println(integerSet.stream().sorted((a, b) -> 0).parallel().collect(Collectors.toList()));
System.out.println(integerSet.stream().sorted((a, b) -> 0).collect(Collectors.toList()));

[-34, 45356, 47424, 234, -23, 234234, 1, 34234, 3, 4, 0]
[-34, 45356, 47424, 234, -23, 234234, 1, 34234, 3, 4, 0]
[-34, 45356, 47424, 234, -23, 234234, 1, 34234, 3, 4, 0]

Set<String> stringSet = Set.of("aadad", "Z", "vsadasd", "zadad", "C", "Aadasd");
System.out.println(stringSet);
System.out.println(stringSet.stream().sorted((a, b) -> 0).collect(Collectors.toList()));
System.out.println(stringSet.stream().sorted((a, b) -> 0).parallel().collect(Collectors.toList()));

[zadad, Z, vsadasd, C, Aadasd, aadad]
[zadad, Z, vsadasd, C, Aadasd, aadad]
[zadad, Z, vsadasd, C, Aadasd, aadad]

最佳答案

sorted(Comparator) 的 javadoc说:

For ordered streams, the sort is stable.

For unordered streams, no stability guarantees are made.

当然,对于无序流,“身份”排序并不是真正的事情,所以是的,“常数比较器”是一个“身份顺序”,在那个有序 流保持其顺序,无序 流保持无序。

关于java - Comparator 的等价恒等运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58782898/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com