POJO类
class FriendInfo {
private long id;
private String name;
private Integer age;
private String deptId;
public String getDeptId() { return deptId; }
public void setDeptId(String deptId) { this.deptId = deptId; }
public long getId() { return id; }
public void setId(long id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public Integer getAge() { return age; }
public void setAge(Integer age) { this.age = age; }
public FriendInfo(long id, String name, Integer age, String deptId) {
this.id = id;
this.name = name;
this.age = age;
this.deptId = deptId;
}
}
一些Stream操作
class Streamtest{
public static void main(String[] args) {
FriendInfo daxiong = new FriendInfo(123123231, "daxiong", 11, "1");
FriendInfo wangzai = new FriendInfo(123124122, "wangzai", 16, "1");
FriendInfo panghu = new FriendInfo(1231234112, "panghu", 10, "2");
List<FriendInfo> friendInfoList = new ArrayList<>();
friendInfoList.add(wangzai);
friendInfoList.add(daxiong);
friendInfoList.add(panghu);
Integer c = friendInfoList.stream().collect(Collectors.mapping(FriendInfo::getAge, Collectors.reducing((s1, s2) -> s1 > s2 ? s1 : s2))).get();
Object s = friendInfoList.stream().collect(Collectors.mapping(FriendInfo::getName , Collectors.toList() )).stream().reduce( (x,y) -> x+y).get().length();
System.out.println(s);
friendInfoList.stream().filter(n -> n.getAge() > 10).collect(Collectors.toList()).forEach(n -> System.out.println(n.getName()));
friendInfoList.stream().mapToInt(FriendInfo::getAge).boxed().collect(Collectors.toList()).forEach(System.out::println);
friendInfoList.stream().sorted(Comparator.comparing(FriendInfo::getAge)).collect(Collectors.toList()).forEach(n -> System.out.println(n.getName()));
Map<Long, FriendInfo> friendInfoMap = new HashMap<>();
friendInfoMap = friendInfoList.stream().collect(Collectors.toMap(n -> n.getId(), n -> n));
System.out.println(friendInfoMap);
Map<String, List<FriendInfo>> deptToInfo = friendInfoList.stream().collect(Collectors.groupingBy(FriendInfo::getDeptId));
System.out.println(deptToInfo);
Map<String, Long> deptToNumber = friendInfoList.stream().collect(Collectors.groupingBy(FriendInfo::getDeptId, Collectors.counting()));
System.out.println(deptToNumber);
Map<String, List<String>> deptToName = friendInfoList.stream().collect(Collectors.groupingBy(FriendInfo::getDeptId, Collectors.mapping(FriendInfo::getName, Collectors.toList())));
System.out.println(deptToName);
String nameJoin = friendInfoList.stream().collect(Collectors.mapping(FriendInfo::getName, Collectors.joining()));
System.out.println(nameJoin);
}
}