比较然后比较会得到编译错误
2022-09-03 02:42:48
我正在尝试使用Java8按姓名排序员工,然后使用年龄,我已经在下面创建了,但它给了我一个编译器错误List
Comparator
Comparator
Type mismatch: cannot convert from Comparator<Object> to <unknown>
Comparator<String> c = Comparator.comparing(s -> s.split("\\s+")[0])
.thenComparingInt(s -> Integer.parseInt(s.split("\\s+")[1])); //compile error
但是如果我显式指定类型,它的工作原理
Comparator<String> c = Comparator.<String, String> comparing(s -> s.split("\\s+")[0])
.thenComparingInt(s -> Integer.parseInt(s.split("\\s+")[1])); //works
或通过创建两个 s 和链Compartor
Comparator<String> name = Comparator.comparing(s -> s.split("\\s+")[0]);
Comparator<String> age = Comparator.comparingInt(s -> Integer.parseInt(s.split("\\s+")[1]));
Comparator<String> cc = name.thenComparing(age); //works
我已经在左侧指定了类型,但是为什么自动类型推断没有找到正确的类型并期望显式指定。Comparator<String>
有人可以澄清这一点吗?
这是代码
String[] arr = { "alan 25", "mario 30", "alan 19", "mario 25" };
Comparator<String> c = Comparator.<String, String> comparing(s -> s.split("\\s+")[0])
.thenComparingInt(s -> Integer.parseInt(s.split("\\s+")[1]));
List<String> sorted = Arrays.stream(arr).sorted(c).collect(Collectors.toList());
System.out.println(sorted);
输出
[alan 19, alan 25, mario 25, mario 30]