如何在Java中使用多行lambda表达式对int[]进行排序

huangapple go评论79阅读模式
英文:

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) -&gt; {
    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) -&gt; {
    // 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,那么这将适用于listsarrays。假设您的groupage字段是整数。

		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&lt;Item&gt; comp = (o1, o2) -&gt; {
			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.

huangapple
  • 本文由 发表于 2020年4月7日 23:57:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/61084209.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定