一、max 和 min 函数
二、实战
> 执行结果
一、max 和 min 函数
-
最大值 和 最小值
二、实战
@NoArgsConstructor
@AllArgsConstructor
@Data
public class User {
private int id;
private String name;
private String pwd;
private int age;
public User(String name, int age) {
this.name = name;
this.age = age;
}
public User(int id, String name, String pwd) {
this.id = id;
this.name = name;
this.pwd = pwd;
}
}
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
public class Max_MinDemo {
public static void main(String[] args) {
List<User> list = Arrays.asList(new User("花无缺", 18), new User("小鱼儿", 18)
, new User("邀月", 38), new User("怜星", 35));
Optional<User> optionalUser = list.stream().max((s1, s2) ->
Integer.compare(s1.getAge(), s2.getAge())
);
User user = optionalUser.get();
System.out.println("最大年龄:" + user);
optionalUser = list.stream().min((s1, s2) ->
Integer.compare(s1.getAge(), s2.getAge())
);
user = optionalUser.get();
System.out.println("最小年龄:" + user);
optionalUser = list.stream().min(Comparator.comparingInt(User::getAge));
user = optionalUser.get();
System.out.println("【第二种写法】最小年龄:" + user);
}
}
文章来源:https://uudwc.com/A/jrba8
> 执行结果
文章来源地址https://uudwc.com/A/jrba8