Stream 流
eg:
菜肴:Dish.java
@Data
public class Dish {
private String name;
private boolean vegetarian;
private int calories;
private Type type;
public Dish(){}
public Dish(String name, boolean vegetarian, int calories,Type type) {
this.name = name;
this.vegetarian = vegetarian;
this.calories = calories;
this.type=type;
}
}
类型:Type.java
@Data
public class Type {
private String typeName;
private Type(){}
public Type(String typeName){
this.typeName= typeName;
}
}
test.java
@Test
void contextLoads() {
List<Dish> dishList = new ArrayList<>();
dishList.add(new Dish("红烧肉",false,600,new Type("肉菜")));
dishList.add(new Dish("红烧鱼",false,10000,new Type("肉菜")));
dishList.add(new Dish("佛跳墙",false,20000,new Type("肉菜")));
dishList.add(new Dish("香菇青菜",false,200,new Type("素菜")));
dishList.add(new Dish("醋溜白菜",false,100,new Type("素菜")));
System.out.println(afterJava8(dishList).toString());
}
private List<String> afterJava8(List<Dish> dishList) {
return dishList.stream()
.filter(d -> d.getCalories() < 400) //筛选出卡路里小于400的菜肴
.sorted(comparing(Dish::getCalories)) //根据卡路里进行排序(升序)
.map(Dish::getName) //提取菜肴名称
.collect(Collectors.toList()); //转换为List
}
生成流的5种方式
-
通过集合
List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5); Stream<Integer> stream = integerList.stream();
-
通过数组
int[] intArr = new int[]{1, 2, 3, 4, 5}; IntStream stream = Arrays.stream(intArr);
-
通过值
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5);
-
通过文件生成
Stream<String> lines = Files.lines(Paths.get("data.txt"), Charset.defaultCharset())
-
通过函数生成 提供了iterate和generate两个静态方法从函数中生成流
Stream<Integer> stream = Stream.iterate(0, n -> n + 2).limit(5); Stream<Double> stream = Stream.generate(Math::random).limit(5);
使用的方法
filter筛选
List<Integer> integerList = Arrays.asList(1, 1, 2, 3, 4, 5);
Stream<Integer> stream = integerList.stream().filter(i -> i > 3);
distinct去除重复元素
List<Integer> integerList = Arrays.asList(1, 1, 2, 3, 4, 5);
Stream<Integer> stream = integerList.stream().distinct();
limit返回指定流个数
List<Integer> integerList = Arrays.asList(1, 1, 2, 3, 4, 5);
Stream<Integer> stream = integerList.stream().limit(3);
skip跳过流中的元素
List<Integer> integerList = Arrays.asList(1, 1, 2, 3, 4, 5);
Stream<Integer> stream = integerList.stream().skip(2);
统计流中元素个数
1.通过count
List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5);
Long result = integerList.stream().count();
2.通过counting
List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5);
Long result = integerList.stream().collect(counting());
查询
1.findFirst查找第一个
List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5);
Optional<Integer> result = integerList.stream().filter(i -> i > 3).findFirst();
2.findAny随机查找一个
List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5);
Optional<Integer> result = integerList.stream().filter(i -> i > 3).findAny();
查询结果一样