测试实体类
public class User {
private String id;
private String name;
private Integer age;
private Integer sex;
public User() {
}
public User(String id, String name, Integer age, Integer sex) {
this.id = id;
this.name = name;
this.age = age;
this.sex = sex;
}
.....省略get set
}
List<User> userList=new ArrayList<>();
userList.add(new User("1","test-1",21,1));
userList.add(new User("1","test-1",17,0));
userList.add(new User("1","test-1",17,0));
userList.add(new User("1","test-1",18,1));
1.filter 对元素进行过滤,当过滤条件为true时返回对应元素
List<User> userTmp = userList.stream().
filter(user -> user.getSex() == 0).
collect(Collectors.toList());
System.out.println(userTmp.size());
List<User> userTmp2 = userList.stream().
filter(user -> user.getSex() == 0)
.peek(user -> user.setAge(17))
.collect(Collectors.toList());
System.out.println(userTmp2.size());
2.sorted 对元素按指定规则进行排序
List<User> newUserList2=userList.stream().sorted((user1,user2)->{
return user1.getAge().compareTo(user2.getAge());
}).collect(Collectors.toList());
List<User> newUserList = userList.stream().
sorted(Comparator.comparing(User::getAge)).
collect(Collectors.toList());
newUserList2.forEach(System.out::println);
List<User> newUserList = userList.stream().
sorted(Comparator.comparing(User::getAge).reversed())
.collect(Collectors.toList());
newUserList2.forEach(System.out::println);
3.map
List<String> ids = userList.stream().map(user -> user.getId()).collect(Collectors.toList());
ids.forEach(System.out::println);
4.mapToDouble、mapToInt、mapToLong
double asDouble = userList.stream().mapToLong(User::getAge).average().getAsDouble();
System.out.println(asDouble);
Double avgAge = userList.stream().collect(Collectors.averagingDouble(User::getAge));
System.out.println(avgAge);
int maxAge = userList.stream().mapToInt(User::getAge).max().getAsInt();
System.out.println(maxAge);
int minAge = userList.stream().mapToInt(User::getAge).min().getAsInt();
System.out.println(minAge);
long sumAge = userList.stream().mapToLong(user -> user.getAge()).sum();
System.out.println(sumAge);
4.count从Stream中获取指定元素数量
long count = userList.stream().filter(user -> user.getSex() == 0).count();
5.limit获取指定数量的元素
List<User> newUserList = userList.stream().limit(2).collect(Collectors.toList());
newUserList.forEach(System.out::println);
6.skip 跳过指定个数的元素获取后面的元素
List<User> newUserList = userList.stream().skip(2).collect(Collectors.toList());
newUserList.forEach(System.out::println);
7.map转list
Map<String, User> collect = userList.stream().collect(Collectors.toMap(user -> user.getId(), user -> user));
8.去重
List<User> users = userList.stream().
collect(collectingAndThen(
toCollection(() -> new TreeSet<>(comparingLong(User::getAge))), ArrayList::new));