Java8实战--引入流

时间:2022-07-23
本文章向大家介绍Java8实战--引入流,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
  1. 什么是流? 流是Java API的新成员,它允许你以声明性方式处理数据集合(通过查询语句来表达,而不 是临时编写一个实现)。就现在来说,你可以把它们看成遍历数据集的高级迭代器。此外,流还可以透明地并行处理,你无需写任何多线程代码。

啥话少说直接上代码:

  //创建一个list类 里面包含一个对象Dish且创建Dish
  List<Dish> menu = Arrays.asList(
new Dish("pork", false, 800, Dish.Type.MEAT), 3 new Dish("beef", false, 700, Dish.Type.MEAT),
new Dish("", false, 400, Dish.Type.MEAT),
new Dish("french fries", true, 530, Dish.Type.OTHER),
new Dish("rice", true, 350, Dish.Type.OTHER),
new Dish("season fruit", true, 120, Dish.Type.OTHER),
new Dish("pizza", true, 550, Dish.Type.OTHER),
new Dish("prawns", false, 300, Dish.Type.FISH), 5 new Dish("salmon", false, 450, Dish.Type.FISH) );

 Dish类的定义是:
public class Dish {
    private final String name;
    private final boolean vegetarian;
    private final int calories;
    private final Type type;
public Dish(String name, boolean vegetarian, int calories, Type type) { this.name = name;
this.vegetarian = vegetarian;
this.calories = calories;
        this.type = type;
    }
    public String getName() {
        return name;
}
    public boolean isVegetarian() {
        return vegetarian;
}
    public int getCalories() {
        return calories;
       } 
public Type getType() {
    return type;
}
@Override
public String toString() {
    return name;
}
public enum Type { MEAT, FISH, OTHER }
}

现在我们用这两个集合和对象进行离操作

  1. 如果我们想将菜单里面的热量高于350的事物筛选出来:
List<Dish> collect = getDishes().stream().filter(t -> t.getCalories() > 350).collect(toList());
  1. 但是我们现在不要整个Dish对象 只要其中的某一个对象信息如只要菜名:
List<String>  collect1 = getDishes().stream().filter(t -> t.getCalories() > 350).map(Dish::getName).collect(toList());
  1. 如果我们只想要筛选的菜名出来的前三个值:
List<String> collect2 = getDishes().stream().filter(t -> t.getCalories() > 350).limit(3).map(Dish::getName).collect(toList());
  1. 如果我们不想要热量大于350的前两个菜:
List<String> collect2 = getDishes().stream().filter(t -> t.getCalories() > 350).skip(3).map(Dish::getName).collect(toList());//当查出来的元素小于3的时候则返回数据为空
  1. 当我们需要将菜名的字母联合起来去掉重复的字母:
List<String> collect4 = getDishes().stream().map(Dish::getName).map(t -> t.split("")).flatMap(Arrays::stream).distinct().collect(toList());
  1. 查看菜单中是否至少有一个重复的菜品:
if( getDishes().stream().anyMatch(Dish::isVegetarian)){
System.out.println("The menu is (somewhat) vegetarian friendly!!");
}

7.查看菜单中所有的菜是否热量都是大于350的:

boolean isHealthy = getDishes().stream()
                          .allMatch(d -> d.getCalories() >350);
  1. 查找菜单中的某一个菜:
getDishes().stream().filter(t -> t.getCalories()==500).findAny().ifPresent(t -> System.out.println("获取菜名"+t.getName()));//如果这个菜有的话才会打印没有的话是不会打印的
  1. 查找菜单中热量为100的第一个菜的热量
getDishes().stream().filter(t -> t.getCalories() == 100).findFirst().ifPresent(d->System.out.println(d.getName()));
  1. 将菜单中的所有菜的热量加起来:
Integer reduce = getDishes().stream().map(Dish::getCalories).reduce(0, (a, b) -> a + b);//从零开始加加所有元素
  1. 获取热量最高的菜品名字