public class AdjustTests {
public static void main(String[] args){
Person p1 = new Person(1,"张三","男",18,new BigDecimal(100));
Person p2 = new Person(2,"李四","女",16,new BigDecimal(200));
Person p3 = new Person(3,"王五","男",18,new BigDecimal(300));
Person p4 = new Person(4,"赵六","男",18,new BigDecimal(400.5));
Person p5 = new Person(5,"田七","女",16,new BigDecimal(500));
List<Person> list = Arrays.asList(p1, p2, p3, p4, p5);
System.out.println(list);
//集合只保留男性
List<Person> list1 = list.stream().filter(p -> "男".equals(p.getSex())).collect(Collectors.toList());
System.out.println(list1);
//集合只保留男性,且对所有男性的账号金额求和
BigDecimal sumAccount = list.stream().filter(p -> "男".equals(p.getSex())).map(Person::getAccount).reduce(BigDecimal.ZERO, BigDecimal::add);
System.out.println(sumAccount);
//根据年龄和性别分组,并求出分组后账户的总金额
Map<String, Person> accountMap = list.stream().collect(Collectors.toMap(
p -> String.valueOf(p.getAge()) + "_" + p.getSex()
, Function.identity()
, (t1, t2) -> {
t2.setAccount(t2.getAccount().subtract(t1.getAccount()));
return t2;
}
));
System.out.println(accountMap);
//根据工资倒叙排序
List<Person> newList = list.stream().sorted(Comparator.comparing(Person::getAccount).reversed()).collect(Collectors.toList());
System.out.println(newList);
//多条件排序
List<Person> newList1 = list.stream().filter(p -> p.getAccount() != null).sorted(Comparator.comparing(Person::getSex).thenComparing(Person::getAccount)).collect(Collectors.toList());
System.out.println(newList1);
//求最小值
BigDecimal account = newList.stream().min(Comparator.comparing(Person::getAccount)).get().getAccount();
System.out.println(account);
//判断是否为空
Optional.ofNullable(p1).map(u -> u.getName()).get();
//判读是否为空,抛异常
Person p = null;
String s = Optional.ofNullable(p).map(u -> u.getName()).orElse("0");
try {
Optional.ofNullable(p).map(u -> u.getName()).orElseThrow(() -> new Exception("132"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
class Person {
private Integer id;
private String name;
private String sex;
private Integer age;
private BigDecimal account;
private BigDecimal count;
public Person(Integer id, String name, String sex, Integer age, BigDecimal account) {
this.id = id;
this.name = name;
this.sex = sex;
this.age = age;
this.account = account;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public BigDecimal getAccount() {
return account;
}
public void setAccount(BigDecimal account) {
this.account = account;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public BigDecimal getCount() {
return count;
}
public void setCount(BigDecimal count) {
this.count = count;
}
@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + '\'' +
", sex='" + sex + '\'' +
", age=" + age +
", account=" + account +
'}';
}