Java8的Stream流的使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/winteriscomming/article/details/82789492

参考自 原作者

//过滤出蔬菜食物
List<Food> vegetablesFood= menu.stream().filter(Food::isVegetable).collect(Collectors.toList());

 

//过滤出偶数,并且不重复的元素。
List<Integer> numbers = Arrays.asList(1, 2, 1, 3, 3, 2, 4);
numbers.stream().filter(i->i%2==0).distinct().forEach(System.out::println);

 

//截断流  热量大于300卡路里的食物        解析?
List<Food> foodList = allFoodList.stream().filter(f->f.getCalories()>300).limit(3).collect(toList());
//跳过元素  热量大于300卡路里的食物     解析?
List<Food>foodList = allFoodList.stream().filter(f->f.getCalories()>300).skip(2).collect(toList());
//映射            为啥不是f.getName()呢?
List<String> foodNameList = allFoodList.stream().map(Food::getName).collet(toList());

List<String> foodNameList = Arrays.asList("apple","pear","balana","tomato","onion");
List<Integer>wordLengthList = foodNameList.stream().map(String::length).collect(toList);
//展开流
String words = "Hello world"
List<String> uniqueCharacters = words.stream().map(w->w.split("")).flatMap(Arrays::stream).distinct().collet(Collectors.toList());

 

/*
 *查找和匹配
 *
 */
//任意匹配    判断的条件里,任意一个元素匹配成功,返回true
if(allFoodList.stream().anyMatch(Food::isVegetable)){
    System.out.println("The food is so good!");
}
//全部匹配       判断条件里的元素,所有的都是XXX时候,返回true
Boolean isHealthy = allFoodList.stream().allMatch(f->f.getCalories<1000);
//全部不匹配    判断条件里的元素,所有的都不是XXX时候,返回true
Boolean isHealthy = allFoodList.stream().noneMatch(f->f.getCalories<1000);
//获取任意一个元素  
Optional<Food> food = allFoodList.stream().filter(Food::isVegetable).findAny();


/*
 *归约   将一个流中的元素,反复结合运算得到一个值
 */
//使用循环求和
List<Integer> numbers = new ArrayList<Integer>();
int sum = 0;
for(int x:numbers){
    sum+=x;
}

//使用流的API求和
int sum2 = numbers.stream().reduce(0,(a,b)->a+b);

 

//求最大值
Optional<Integer> max = numbers.stream().reduce(Integer::max);

//求最小值
Optional<Integer> min = numbers.stream().reduce(Integer::min);

//使用reduce相对于使用逐步迭代的好处在于,外部迭代改成了内部迭代,在需要实现并行执行的操时作变得简单。

 

 

猜你喜欢

转载自blog.csdn.net/winteriscomming/article/details/82789492