1.基础数据
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {private String name;private Integer age;private String sex;private String city; //城市private Integer money; //业绩金额
}
//准备数据List<User> users = new ArrayList<>();users.add(new User("京爷1",21,"男","北京",1200));users.add(new User("京爷2",21,"男","北京",2100));users.add(new User("海哥1",23,"女","上海",3200));users.add(new User("海哥2",30,"女","上海",2600));users.add(new User("苏姐1",21,"男","苏州",2800));users.add(new User("苏姐2",21,"男","苏州",1500));
2.根据城市分组
Map<String, List<User>> collect = users.stream().collect(Collectors.groupingBy(User::getCity));collect.forEach((k,v)->{System.out.println("城市名:"+ k);System.out.println(v);});
3.列出每个城市的销售冠军
Map<String, Optional<User>> map = users.stream().collect(Collectors.groupingBy(User::getCity,Collectors.maxBy(Comparator.comparingInt(User::getMoney))));
4.求每个城市的销售总金额
Map<String, Integer> map = users.stream().collect(Collectors.groupingBy(User::getCity,Collectors.summingInt(User::getMoney)));
5.全国销售总金额
int sum = users.stream().mapToInt(User::getMoney).sum();System.out.println("全国销售总金额:"+sum);
6.过滤出年龄大于22岁的员工
List<User> collect = users.stream().filter(s -> s.getAge()>22).collect(Collectors.toList());System.out.println(collect);
7. 最好与最差的员工的销售金额
Integer max = users.stream().map(User::getMoney).max(Integer::compareTo).get();System.out.println("业绩最好的员工销售金额:"+max);Integer min = users.stream().map(User::getMoney).min(Integer::compareTo).get();System.out.println("业绩最差的员工销售金额:"+min);
8.人均销售金额
double avg = users.stream().mapToDouble(User::getMoney).average().getAsDouble();
System.out.println("人均销售金额:" + avg );
9. 全国根据销售金额排序
users.sort(Comparator.comparing(User::getMoney).reversed());System.out.println(users);
10. 全国有多少销售城市
List<String> citys = users.stream().map(User::getCity).distinct().collect(Collectors.toList());
System.out.println(citys);