老师,由数值直接构建流,怎么排序?
来源:3-15 实战:流的构建四种形式

慕粉1230329569
2022-02-13
这里应该怎么写
写回答
1回答
-
public static void main(String[] args) { Stream stream = Stream.of(1, 5, 3); stream.sorted().forEach(System.out::println); }
基础类型数据的排序直接用sorted方法就行,方法内部知道如何排序。对于对象类型,sorted方法是不知道如何排序的,所以需要指定排序字段
package com.company; import java.util.Comparator; import java.util.stream.Stream; public class Main { static class Person { // 年龄 private Integer age; // 体重 private Integer weight; public Person(Integer age, Integer weight) { this.age = age; this.weight = weight; } public Integer getAge() { return age; } public Integer getWeight() { return weight; } @Override public String toString() { return "Person{" + "age=" + age + ", weight=" + weight + '}'; } } public static void main(String[] args) { Stream<Person> stream = Stream.of( new Person(20, 110), // 20岁 110斤 new Person(25, 160), // 25岁 160斤 new Person(23, 180)); // 23岁 180斤 stream // 单纯使用sorted排序,程序不知道用Person的哪个字段排,所以需要使用Comparator指定排序字段 .sorted(Comparator.comparing(Person::getWeight)) .forEach(System.out::println); } }
012022-02-13
相似问题