求和:
Stream<Integer> integerStream = Stream.of(10, 30, 33); Optional<Integer> reduce = integerStream.reduce(new BinaryOperator<Integer>() { @Override public Integer apply(Integer integer, Integer integer2) { return integer + integer2; } }); System.out.printf(String.valueOf(reduce.get()));
求最大、最小值:
ArrayList<User> userEntities = new ArrayList<>(); userEntities.add(new User("mayikt", 20)); userEntities.add(new User("meite", 28)); userEntities.add(new User("zhangsan", 35)); userEntities.add(new User("xiaowei", 16)); Stream<User> stream = userEntities.stream(); // Optional<User> max = stream.max(new Comparator<User>() { // @Override // public int compare(User o1, User o2) { // return o1.getAge() - o2.getAge();//最大 // } // }); Optional<User> min = stream.max(new Comparator<User>() { @Override public int compare(User o1, User o2) { return o2.getAge() - o1.getAge();//最小 } }); System.out.printf(String.valueOf(min.get().getAge())); }
字符串的比较:
ArrayList<User> userEntities = new ArrayList<>(); userEntities.add(new User("mayikt", 20)); userEntities.add(new User("meite", 28)); userEntities.add(new User("zhangsan", 35)); userEntities.add(new User("xiaowei", 16)); Stream<User> stream = userEntities.stream(); //比字符串 boolean b = stream.anyMatch(new Predicate<User>() { @Override public boolean test(User user) { return "xiaowei".equals(user.getUserName()); } }); System.out.println(b);
分页:
ArrayList<User> userEntities = new ArrayList<>(); userEntities.add(new User("mayikt", 20)); userEntities.add(new User("meite", 28)); userEntities.add(new User("zhangsan", 35)); userEntities.add(new User("xiaowei", 16)); Stream<User> stream = userEntities.stream(); // stream.limit(2).forEach(user -> System.out.println(user)); stream.skip(2).limit(3).forEach(user -> System.out.println(user));
排序:
ArrayList<User> userEntities = new ArrayList<>(); userEntities.add(new User("mayikt", 20)); userEntities.add(new User("meite", 28)); userEntities.add(new User("zhangsan", 35)); userEntities.add(new User("xiaowei", 16)); Stream<User> stream = userEntities.stream(); //排序 stream.sorted(new Comparator<User>() { @Override public int compare(User o1, User o2) { return o2.getAge()-o1.getAge(); } }).forEach(user -> System.out.println(user));