jdk8中流的使用(一)

流是java API的新成员,是遍历数据集的高级迭代器,流还可以并行处理,无需写任何多线程代码
流定义:从支持数据处理操作的源生成的元素序列

stream API特点:
1.声明性——更简洁,更易读 
2. 可复合——更灵活 
3.可并行——性能更好 

流和集合区别:
集合是一个内存中的数据结构,它包含数据结构中目前所有的值-----集合中的每个元素都得选算出来才能添加到集合中
流则是在概念上固定的数据结构(你不能添加和删除元素),其元素则是按需计算的

流的使用:

筛选和切片
一:筛选
public static List<Dish> dishInitToList() {
    List<Dish> menu = Arrays.asList(new Dish("pork", false, 800, Type.MEAT), new Dish("beef", false, 700, Type.MEAT),
        new Dish("chicken", false, 400, Type.MEAT), new Dish("french fries", true, 530, Type.OTHER),
        new Dish("rice", true, 350, Type.OTHER), new Dish("season fruit", true, 120, Type.OTHER),
        new Dish("pizza", true, 550, Type.OTHER), new Dish("prawns", false, 300, Type.FISH),
        new Dish("salmon", false, 450, Type.FISH));
    return menu;
  }
1.用谓词筛选
Streams接口支持filter方法(你现在应该很熟悉了)。该操作会接受一个词(一个返回 boolean的函数)作为参数,并返回一个包括所有符合谓词的元素的流
需求:筛选出所有的素菜
List<Dish> vegetarianMenu=MenuUtils.dishInitToList()
                                 .stream()
                                 .filter(Dish::isVegetarian).collect(Collectors.toList());
2.筛选各异的元素
流还支持一个叫作distinct的方法,它会返回一个元素各异(根据流所生成元素的 hashCode和equals方法实现)的流
需求:筛选列表中所有的偶数,并且保证不重复
List<Integer> numbers = Arrays.asList(1, 2, 1, 3, 3, 2, 4);
numbers.stream().filter(i -> i % 2 == 0).distinct().forEach(System.out::println);
3.截短流
流支持limit(n)方法,该方法会返回一个不超过给定长度的流。所需的长度作为参数传递 给limit。如果流是有序的,则多会返回前n个元素。
需求:选出热量超过300卡路里的头三道菜
List<Dish> dishs = MenuUtils.dishInitToList().stream().filter(d -> d.getCalories() > 300).limit(3)
        .collect(Collectors.toList());
4.跳过元素
流还支持skip(n)方法,返回一个掉了前n个元素的流。如果流中元素不n个,则返回一 个空流。请注意,limit(n)和skip(n)是互补的
需求:跳过超过300卡路里的头两道菜,并返回剩下的
List<Dish> dishs2 = MenuUtils.dishInitToList().stream().filter(d -> d.getCalories() > 300).skip(2)
        .collect(Collectors.toList());

二.映射
一个非常常见的数据处理套路就是从某些对象中选择信息。比如在SQL里,你可以从表中选 择一列。Stream API也通过map和flatMap方法提供了类似的工具。 
1.对流中每一个元素应用函数:map方法
System.out.println("map()方法的使用:------------------>");
    List<String> dishNames = MenuUtils.dishInitToList().stream().map(Dish::getName).collect(Collectors.toList());
    dishNames.stream().forEach(System.out::println);
找到原list中所有的名称,并返回一个新的集合
2.流的扁平化:flatMap方法使用
需求:给定["GoodBye", "World"],希望返回["G","o","d","B","y","e", "W","r","l"]
String[] arrayOfWords = { "GoodBye", "World" };
    Stream<String> words = Arrays.stream(arrayOfWords);
    List<String> w = words.map(s -> s.split("")).flatMap(Arrays::stream).distinct().collect(Collectors.toList());
    w.stream().forEach(System.out::println);
 

posted @ 2019-08-17 10:35  小草1234  阅读(207)  评论(0编辑  收藏  举报