# java中一个基本类型的数组怎么使用lambda进行排序？

cc12 发布于 07/18 18:44

2

```int a[] ={22,33,52,43,78,91,12,9,4,99};
a=IntStream.of(a).sorted().toArray();
System.out.println(Arrays.toString(a));```

0

0

``````import java.util.List;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.stream.Collectors;

public class A1 {

static void sortInt(int[] a , boolean ascending ) {
List<Integer> list = new ArrayList<>();
for(int n:a)
if (ascending)
System.out.println(" 升序排列：" + list.stream().sorted().collect(Collectors.toList()));
else
System.out.println(" 降序排列：" + list.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList()));
}

public static void main(String arg[]){
int a[] ={22,33,52,43,78,91,12,9,4,99};
sortInt(a, true);
sortInt(a, false);
}
}``````
``````D:\java\test\OS_China>javac A1.java

D:\java\test\OS_China>java A1
升序排列：[4, 9, 12, 22, 33, 43, 52, 78, 91, 99]
降序排列：[99, 91, 78, 52, 43, 33, 22, 12, 9, 4]

D:\java\test\OS_China>``````

``````import java.util.List;
import java.util.ArrayList;
public class A {

static void sortDouble(double[] a , boolean ascending ) {
List<Double> list = new ArrayList<>();
for(double d:a)
if (ascending){
list.sort((a1,a2)->a1.compareTo(a2));
System.out.println(" 升序排列：" + list);
} else{
list.sort((a1,a2)->a2.compareTo(a1));
System.out.println(" 降序排列：" + list);
}
}
public static void main(String arg[]){
double a[] ={21.2,32.3,53.2,44.39,87.8,91.1,12.2,91.0,45.0,99.9};
sortDouble(a, true);
sortDouble(a, false);
}
}``````

DOS 窗口：

``````D:\java\test\OS_China>java -version
java version "1.8.0_162"
Java(TM) SE Runtime Environment (build 1.8.0_162-b12)
Java HotSpot(TM) 64-Bit Server VM (build 25.162-b12, mixed mode)

D:\java\test\OS_China>javac A.java

D:\java\test\OS_China>java A
升序排列：[12.2, 21.2, 32.3, 44.39, 45.0, 53.2, 87.8, 91.0, 91.1, 99.9]
降序排列：[99.9, 91.1, 91.0, 87.8, 53.2, 45.0, 44.39, 32.3, 21.2, 12.2]

D:\java\test\OS_China>``````