Java 8系列之Stream的基本语法详解--02

Stream流是java8中很重要的一项技能:

之前操作java代码, 执行过滤操作:

public class SimpleStream {

    public static void main(String[] args) {

        List<Dish> menu = Arrays.asList(
                new Dish("pork", false, 800, Dish.Type.MEAT),
                new Dish("beef", false, 700, Dish.Type.MEAT),
                new Dish("chicken", 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),
                new Dish("salmon", false, 450, Dish.Type.FISH) );

        List<String> names = getDishNamesByCollections(menu);
        System.out.println(names);
    }

    private static List<String> getDishNamesByCollections(List<Dish> menu){
        List<Dish> lowCal = new ArrayList<>();
//遍历 for (Dish dish : menu) { if (dish.getCalories() < 400){ lowCal.add(dish); } } //排序 Collections.sort(lowCal, (d1, d2) -> Integer.compare(d1.getCalories(), d2.getCalories())); List<String> dishNameList = new ArrayList<>();
     //遍历 for (Dish d : lowCal) { dishNameList.add(d.getName()); } return dishNameList; } }

  可以把上面的代码以Stream的形式来做:

//stream方法来做
private static List<String> getDishNamesByStream(List<Dish> menu){
    //先过滤,然后排序,最后以map的key,返回集合
    List<String> collect = menu.stream().filter(dish -> dish.getCalories() < 400)
                .sorted(Comparator.comparing(Dish::getCalories)).map(Dish::getName).collect(Collectors.toList());

    return collect;
}

  

 create stream

public class CreateStream {

    private static Stream<String> createStreamFromCollection(){
        List<String> list =  Arrays.asList("helo", "alex", "world");
        return list.stream();
    }

    public static void main(String[] args) throws Exception {
        createStreamFromCollection().forEach(System.out::println);
        //of
        Stream<String> helo = Stream.of("helo", "alex", "world");

        //Arrays
        Stream<Object> stream = Arrays.stream(new String[]{"helo", "alex", "world"});

        //File Stream
        Path path = Paths.get("D:\\tools\\Stream.txt");
        try(Stream<String> lines = Files.lines(path)) {
            lines.forEach(System.out::println);

        }catch (Exception e){
            throw new Exception(e);
        }
    }
}

  

Stream 的关键字

Filter

public class StreamFilter {

    public static void main(String[] args) {

        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6,7, 6);
        //filter: 过滤
        List<Integer> integers = list.stream().filter(d -> d % 2 == 0).collect(Collectors.toList());
        System.out.println(integers);

        //distinct: 去重
        integers = list.stream().distinct().collect(Collectors.toList());
        System.out.println(integers);

        //skip: 跳过前几位
        List<Integer> skipList = list.stream().skip(4).collect(Collectors.toList());
        skipList.stream().forEach(System.out::println);

        //limit: 选取前几位
        List<Integer> limitList = list.stream().limit(4).collect(Collectors.toList());
        limitList.stream().forEach(System.out::println);

    }
}

  

Map:

public class StreamMap {

    private static List<Dish> listDish(){
        List<Dish> menu = Arrays.asList(
                new Dish("pork", false, 800, Dish.Type.MEAT),
                new Dish("beef", false, 700, Dish.Type.MEAT),
                new Dish("chicken", 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),
                new Dish("salmon", false, 450, Dish.Type.FISH) );
        return menu;
    }
    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 6);
        //map:
        List<Integer> result = list.stream().map(i -> i * 2).collect(Collectors.toList());
        System.out.println(result);


        listDish().stream().map(d -> d.getName()).forEach(System.out::println);
        List<String> dishs = listDish().stream().map(d -> d.getName()).collect(Collectors.toList());
        System.out.println(dishs);

        //flatMap : 扁平化 把多个合并到一起
    }
}

  

match:

public class StreamMatch {

    public static void main(String[] args) {
        Stream<Integer> stream = Arrays.stream(new Integer[]{-1, 1,2,3,4,5,6,7});
        //allMatch: 所有都满足
        boolean match = stream.allMatch(i -> i > 0);
        System.out.println(match);

        //anyMatch: 任意一个满足
        stream = Arrays.stream(new Integer[]{-1, 1,2,3,4,5,6,7});
        boolean anyMatch = stream.anyMatch(i -> i > 0);
        System.out.println(anyMatch);

        //noneMatch: 没有一个满足
        stream = Arrays.stream(new Integer[]{ 1,2,3,4,5,6,7});
        boolean noneMatch = stream.noneMatch(i -> i < 0);
        System.out.println(noneMatch);
    }

}

  

find -> optional

public class StreamFind {

    public static void main(String[] args) {
        Stream<Integer> stream = Arrays.stream(new Integer[]{1,2,3,4,5,6,7});
        //findAny: 任务其中一个满足条件的
        Optional<Integer> optional = stream.filter(i -> i % 2 == 0).findAny();
        System.out.println(optional.get());

        stream = Arrays.stream(new Integer[]{1,2,3,4,5,6,7});
        Optional<Integer> optional2 = stream.filter(i -> i > 10).findAny();
        //orElse: optional2中没有满足条件的,给出默认值-1
        System.out.println(optional2.orElse(-1));
    }

}

  

reduce: 聚合

 

public class StreamReduce {

    public static void main(String[] args) {
        Stream<Integer> stream = Arrays.stream(new Integer[]{1,2,3,4,5,6,7});
        Integer sum = stream.reduce(0, (i, j) -> i + j);
        System.out.println(sum);

        //求和
        stream = Arrays.stream(new Integer[]{1,2,3,4,5,6,7});
        stream.reduce((i, j) -> i + j).ifPresent(System.out::println);

        //最大值
        stream = Arrays.stream(new Integer[]{1,2,3,4,5,6,7});
//        stream.reduce((i, j) -> {
//            return i > j ? i : j;
//        }).ifPresent(System.out::println);
        //或
//        stream.reduce(Integer::max).ifPresent(System.out::println);
        //或
        stream.reduce((i, j) -> i > j ? i : j).ifPresent(System.out::println);

        //偶数求和
        stream = Arrays.stream(new Integer[]{1,2,3,4,5,6,7});
        Integer result = stream.filter(i -> i % 2 == 0).reduce(1, (i, j) -> i * j);
        Optional.of(result).ifPresent(System.out::println);

    }
}

 

Collector

public class CollectorIntroduce {

    public static void main(String[] args) {
        List<Apple> menu = Arrays.asList(
                new Apple("green", 150),
                new Apple("yellow", 120),
                new Apple("green", 170),
                new Apple("green", 150),
                new Apple("yellow", 170));

        final Map<String, List<Apple>> stringListMap = groupByNormal(menu);
        System.out.println(stringListMap);
        final Map<String, List<Apple>> stringListMap1 = groupByFunction(menu);
        System.out.println(stringListMap1);
        final Map<String, List<Apple>> stringListMap2 = groupByCollector(menu);
        System.out.println(stringListMap2);

    }

    /**
     * Collector
     * @param apples
     * @return
     */
    private static Map<String, List<Apple>> groupByCollector(List<Apple> apples) {
        return apples.stream().collect(Collectors.groupingBy(Apple::getColor));
    }

    /**
     * Function
     * @param apples
     * @return
     */
    private static Map<String, List<Apple>> groupByFunction(List<Apple> apples) {
        Map<String, List<Apple>> map = new HashMap<>();
        apples.stream().forEach(a ->{
            List<Apple> colorList = Optional.ofNullable(map.get(a.getColor())).orElseGet(() -> {
                List<Apple> list = new ArrayList<>();
                map.put(a.getColor(), list);
                return list;
            });
            colorList.add(a);
        });
        return map;
    }

    /**
     * 常规方式
     * @param apples
     * @return
     */
    private static Map<String, List<Apple>> groupByNormal(List<Apple> apples){
        Map<String, List<Apple>> map = new HashMap<>();
        for (Apple apple : apples) {
            List<Apple> list = map.get(apple.getColor());
            if (null == list){
                list = new ArrayList<>();
                map.put(apple.getColor(), list);
            }
            list.add(apple);
        }
        return map;
    }
}

  

public class StreamAveraging {
        private static List<Dish> menu = Arrays.asList(
                new Dish("pork", false, 800, Dish.Type.MEAT),
                new Dish("beef", false, 700, Dish.Type.MEAT),
                new Dish("chicken", 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),
                new Dish("salmon", false, 450, Dish.Type.FISH) );

    public static void main(String[] args) {
        testAveragingDouble();
        testAveragingInt();
        testAveragingLong();
        testCollectingAndThen();
        testCounting();
        testGroupingByFunction();
        testGroupingByFunctionAndCollector();
        testSummarizingInt();
    }

    private static void testAveragingDouble(){
        Optional.ofNullable(menu.stream().collect(Collectors.averagingDouble(Dish::getCalories)))
                .ifPresent(System.out::println);
    }

    private static void testAveragingInt(){
        Optional.ofNullable(menu.stream().collect(Collectors.averagingInt(Dish::getCalories)))
                .ifPresent(System.out::println);
    }

    private static void testAveragingLong(){
        Optional.ofNullable(menu.stream().collect(Collectors.averagingLong(Dish::getCalories)))
                .ifPresent(System.out::println);
    }

    private static void testCollectingAndThen(){
        Optional.ofNullable(menu.stream().collect(Collectors.collectingAndThen(Collectors.averagingInt(Dish::getCalories), a -> "The Average Cal is ->" + a)))
                .ifPresent(System.out::println);
    }

    private static void testCounting(){
        Optional.ofNullable(menu.stream().collect(Collectors.counting())).ifPresent(System.out::println);
    }

    /**
     * 根据type分组
     */
    private static void testGroupingByFunction(){
        Optional.ofNullable(menu.stream().collect(Collectors.groupingBy(Dish::getType))).ifPresent(System.out::println);
    }

    /**
     * group的个数
     */
    private static void testGroupingByFunctionAndCollector(){
        Optional.ofNullable(menu.stream().collect(Collectors.groupingBy(Dish::getType, Collectors.counting()))).ifPresent(System.out::println);
        Map<Dish.Type, Double> collect = menu.stream().collect(Collectors.groupingBy(Dish::getType, Collectors.averagingInt(Dish::getCalories)));
    }

    /**
     *
     */
    private static void testGroupingByFunctionAndSupplierAndCollector(){
        Map<Dish.Type, Double> collect = menu.stream().collect(Collectors.groupingBy(Dish::getType, TreeMap::new, Collectors.averagingInt(Dish::getCalories)));
        System.out.println(collect.getClass());

    }

    /**
     * summarizingInt
     */
    private static void testSummarizingInt(){
        IntSummaryStatistics summaryStatistics = menu.stream().collect(Collectors.summarizingInt(Dish::getCalories));
        Optional.of(summaryStatistics).ifPresent(System.out::println);

    }
}

  

 

  

 

posted @ 2022-04-16 19:09  IT6889  阅读(213)  评论(0编辑  收藏  举报