Java:使用Lambda表达式对数组进行排序? [英] Java: sorting an array with lambda expression?

查看:845
本文介绍了Java:使用Lambda表达式对数组进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始研究函数式编程和Java 8 lambda.我有一个整数数组,我想按升序对其进行排序.

I've recently got into functional programming and Java 8 lambdas. I have an array of ints and I want to sort it in an ascending order.

我尝试使用lambda进行操作的方式如下:

The way I am trying to do this with lambda is as follows:

Arrays.stream(intArray).sorted((x, y) -> Integer.compare(x, y) == -1);

问题是我的编译器说:

Error:(12, 32) java: method sorted in interface 
java.util.stream.IntStream cannot be applied to given types;
required: no arguments
found: (x,y)->Int[...]== -1
reason: actual and formal argument lists differ in length

我在这里想念什么?

推荐答案

Comparator接受两个Object并返回一个int.

A Comparator takes two Object and returns an int.

在这里,我们输入两个Object,但返回的是布尔表达式(Integer.compare(x, y) == -1)

Here, we're entering with two Object's but are returning a boolean expression (Integer.compare(x, y) == -1)

您实际上只需要它的第一部分

You actually just need the first part of it

Arrays.stream(intArray)
      .sorted((x, y) -> Integer.compare(x, y))
      .toArray(Integer[]::new);


由于您似乎正在使用Integer对象的数组(因为IntStream没有sorted(Comparator)方法),因此最好使用简单的IntStream,它将简化您的生活,因为int将按照其自然顺序进行排序.


Since you seem to be using an array of Integer objects (because an IntStream doesn't have a sorted(Comparator) method) you better be using a simple IntStream, it will simplify your life because the int will than be sorted in their natural order.

返回一个包含此流中已排序元素的流 订单.

Returns a stream consisting of the elements of this stream in sorted order.

Arrays.stream(intArray)
      .mapToInt(x->x)
      .sorted()
      .toArray();

这篇关于Java:使用Lambda表达式对数组进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆