stream求集合元素的属性值最值
Person p1 = new Person("张三", new BigDecimal("10.0"));
Person p2 = new Person("李四", new BigDecimal("30.0"));
Person p3 = new Person("王五", new BigDecimal("40.0"));
Person p4 = new Person("赵六", new BigDecimal("10.0"));
Person p5 = new Person("马七", new BigDecimal("40.0"));
List<Person> list = new ArrayList<>();
list.add(p1);
list.add(p2);
list.add(p3);
list.add(p4);
list.add(p5);
// 最小值
Optional<BigDecimal> result = list.stream().map(Person::getSalary).min(BigDecimal::compareTo);
// 最大值
// Optional<BigDecimal> result = list.stream().map(Person::getSalary).max(BigDecimal::compareTo);
/**
* compareTo
* int a = bigdemical.compareTo(bigdemical2)
* a = -1,表示bigdemical小于bigdemical2;
* a = 0,表示bigdemical等于bigdemical2;
* a = 1,表示bigdemical大于bigdemical2;
*/
List<Person> collect = list.stream().filter(item -> item.getSalary().compareTo(result.get())==0).collect(Collectors.toList());
System.out.println("获取元素最小值:" + collect);
打印结果:
获取元素最小值:[{name='张三', salary=10.0}, {name='赵六', salary=10.0}]
获取元素最大值:[{name='王五', salary=40.0}, {name='马七', salary=40.0}]
纸上得来终觉浅,绝知此事要躬行。