英文:
How to sort int[] with multi-line lambda expression in Java
问题
这个问题有一个关于如何使用多行 lambda 表达式对 List<Integer> 进行排序的回答:
list.sort((o1, o2) -> {
int cmp = o1.getGroup().compareTo(o2.getGroup());
if (cmp == 0)
cmp = Integer.compare(o1.getAge(), o2.getAge());
if (cmp == 0)
cmp = o1.getName().compareTo(o2.getName());
return cmp;
});
不幸的是,对于原始数组 `int[] arr`,这似乎不起作用:
Arrays.sort(arr, (int1, int2) -> {
// 一些 lambda,例如各种 if-else 语句
});
如何在 Arrays.sort() 中使用多行 lambda 表达式来对原始数组进行排序?
只要使用 lambda 表达式(不使用比较器),我可以接受任何其他方法(不必使用 `Arrays.`)。
英文:
This question has an answer for how to sort a List<Integer> with a multi-line lambda expression:
list.sort((o1, o2) -> {
int cmp = o1.getGroup().compareTo(o2.getGroup());
if (cmp == 0)
cmp = Integer.compare(o1.getAge(), o2.getAge());
if (cmp == 0)
cmp = o1.getName().compareTo(o2.getName());
return cmp;
});
Unfortunately, this does not seem to work for a raw array int[] arr
:
Arrays.sort(arr, (int1, int2) -> {
// some lambda, various if-else statements for example
});
How to use a multi-line lambda expression in Arrays.sort() to sort a raw array?
I'm fine with any other approach (does not have to use Arrays.
) as long as it uses lambda expressions (no comparators).
答案1
得分: 1
如果您坚持只使用lambdas
,那么这将适用于lists
和arrays
。假设您的group
和age
字段是整数。
Comparator<Item> comp = (o1, o2) -> {
int cmp = Integer.compare(o1.getGroup(), o2.getGroup());
cmp = cmp == 0 ? Integer.compare(o1.getAge(), o2.getAge()) : cmp;
cmp = cmp == 0 ? o1.getName().compareTo(o2.getName()) : cmp;
return cmp;
};
list.sort(comp);
Arrays.sort(items, comp);
但是我会使用一个List
,并按以下方式处理:
list.sort(Comparator.comparing(Item::getGroup)
.thenComparing(Item::getAge)
.thenComparing(Item::getName));
而且,您的lambda
表达式实际上是一个comparator
。无论如何构造,没有一种方法可以不使用某种形式的Comparator
来进行比较。
英文:
If you're intent on doing it using only lambdas
then this will work with both lists
and arrays
. This presume your group
and age
fields are ints.
Comparator<Item> comp = (o1, o2) -> {
int cmp = Integer.compare(o1.getGroup(), o2.getGroup());
cmp = cmp == 0 ? Integer.compare(o1.getAge(), o2.getAge()) : cmp;
cmp = cmp == 0 ? o1.getName().compareTo(o2.getName()) : cmp;
return cmp;
};
list.sort(comp);
Arrays.sort(items, comp);
But I would use a List
and do it as follows:
list.sort(Comparator.comparing(Item::getGroup)
.thenComparing(Item::getAge)
.thenComparing(Item::getName));
And even your lambda
expression is a comparator
. You can't compare without some sort of Comparator
no matter how you construct it.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论