Stream 使用一种类似用 SQL 语句从数据库查询数据的直观方式来提供一种对 Java 集合运算和表达的高阶抽象。Stream API可以极大提高Java程序员的生产力,让程序员写出高效率、干净、简洁的代码。这种风格将要处理的元素集合看作一种流, 流在管道中传输, 并且可以在管道的节点上进行处理, 比如筛选, 排序,聚合等。
Stream stream = Stream.of("a", "b", "c");
String[] strArray = new String[] { "a", "b", "c" };
stream = Stream.of(strArray);
stream = Arrays.stream(strArray);
List<String> list = Arrays.asList(strArray);
stream = list.stream();
注意:一个Stream流只可以使用一次,这段代码为了简洁而重复使用了数次,因此会抛出 stream has already been operated upon or closed 异常。
Stream<String> stream2 = Stream.of("a", "b", "c");
// 转换成 Array
String[] strArray1 = stream2.toArray(String[]::new);
// 转换成 Collection
List<String> list1 = stream2.collect(Collectors.toList());
List<String> list2 = stream2.collect(Collectors.toCollection(ArrayList::new));
Set set1 = stream2.collect(Collectors.toSet());
Stack stack1 = stream2.collect(Collectors.toCollection(Stack::new));
// 转换成 String
String str = stream.collect(Collectors.joining()).toString();
//实体根据年龄 倒序
List<User> collect1 = users.stream().sorted(Comparator.comparing(User::getName).reversed()).collect(Collectors.toList());
//实体根据年龄 正序
List<User> collect2 = users.stream().sorted(Comparator.comparing(User::getAge)).collect(Collectors.toList());
//直接排序 倒序
List<Integer> collect3 = list.stream().sorted(Comparator.comparing(Integer::intValue).reversed()).collect(Collectors.toList());
//直接排序 正序
List<Integer> collect4 = list.stream().sorted().collect(Collectors.toList());
List<Integer> collect5 = list.stream().sorted(Comparator.comparing(Integer::intValue)).collect(Collectors.toList());
limit 方法用于获取指定数量的流。
//Stream流的limit使用
List<User> collect6 = users.stream().limit(2).collect(Collectors.toList());
List<Integer> collect7 = list.stream().limit(2).collect(Collectors.toList());
skip方法用于从前面扔掉指定数量的流。
//扔掉前n条数据
List<User> collect8 = users.stream().skip(3).collect(Collectors.toList());
List<Integer> collect9 = list.stream().skip(3).collect(Collectors.toList());
List<User> collect10 = users.stream().filter(user -> "王五".equals(user.getName())).collect(Collectors.toList());
List<Integer> collect11 = list.stream().filter(val -> val != 4).collect(Collectors.toList());
map方法用于映射每个元素到对应的结果,一对一。
//修改当前值
List<User> collect12 = users.stream().map(e ->{
if (e.getAge() == 18) {
e.setAge(999);
}
return e;
}).collect(Collectors.toList());
//赋值新的实体
List<UserTwo> collect13 = users.stream().map(e -> {
UserTwo userTwo = new UserTwo();
BeanUtils.copyProperties(e, userTwo);
return userTwo;
}).collect(Collectors.toList());
List<Integer> collect14 = list.stream().map(e -> e * e).collect(Collectors.toList());