java8 新特性实用 练习案例

1.根据苹果的重量筛选,根据苹果的颜色筛选

2.在按重量比较两个苹果之后,你可能想要按原产国排序

3. 一个苹果 既是红色,又重量大于150

4.要么是重(150克以上)的红苹果,要么是绿苹果

5.选出400卡路里以下的菜肴,按照卡路里排序,提取菜肴的名称,只选前3个,将所有名称保存在List中

6.给定单词列表["Hello","World"] ,你想要返回列表 ["H","e","l", "o","W","r","d"]

7.返回当前流中的任意元素

8.计算菜单中的总卡路里

9.统计菜单中菜的个数

10.找出2011年发生的所有交易,并按交易额排序(从低到高)

11.交易员都在哪些不同的城市工作过?

12.查找所有来自于剑桥的交易员,并按姓名排序

13.返回所有交易员的姓名字符串,按字母顺序排序

14.有没有交易员是在米兰工作的?

15.打印生活在剑桥的交易员的所有交易额

16.所有交易中,最高的交易额是多少?

17.找到交易额最小的交易

18.数值流计算菜单的总卡路里

19.数值流应用:勾股数

20.练习:斐波纳契元组序列

(0, 1),(1, 1), (1, 2), (2, 3), (3, 5), (5, 8), (8, 13), (13, 21) ...

21.对交易按照货币分组

22.求出菜单列表的总热量,平均值等

23.得到一个逗号分隔的菜肴名称列表

24.用reducing方法计算菜单的总热量

25.用reduce方法实现 collector的toList方法

26.把热量不到400卡路里的菜划分为“低热量”(diet),热量400到700卡路里的菜划为“普通”(normal),高于700卡路里的划为“高热量”(fat)

27.先按菜单中的类型分组,再按热量(低、中、高)分组

28.计算菜单中每种类型的菜的数量

29.查找每个类型中热量最高的菜

30.求出每种类型的菜的热量和

31.查看每种类型的菜的热量等级(低、中、高)

32.把菜单按照素食和非素食分开

33.把菜单按照素食和非素食分开,再按菜的类型进行分组

34.找到素食和非素食中热量最高的菜

35.按菜的类型进行分组,并将菜名进行拼接

35.CompletableFuture练习

public class Java8Test4 {
    private static List<Dish> menu;
    private static List<Transaction> transactions;
    private static ArrayList<Apple> apples;

    static {
        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));

        Trader raoul = new Trader("Raoul", "Cambridge");
        Trader mario = new Trader("Mario", "Milan");
        Trader alan = new Trader("Alan", "Cambridge");
        Trader brian = new Trader("Brian", "Cambridge");
        transactions = Arrays.asList(new Transaction(brian, 2011, 300), new Transaction(raoul, 2012, 1000),
            new Transaction(raoul, 2011, 400), new Transaction(mario, 2012, 710), new Transaction(mario, 2012, 700),
            new Transaction(alan, 2012, 950));
        Apple apple1 = new Apple("red", 105);
        Apple apple2 = new Apple("green", 103);
        Apple apple3 = new Apple("red", 92);
        Apple apple4 = new Apple("aed", 103);
        apples = Lists.newArrayList(apple1, apple2, apple3, apple4);
    }

    static enum CaloricLevel {
        DIET, NORMAL, FAT
    }

    public static void main(String[] args) {
        try {
            forPractice();
        } catch (Exception e) {
            System.out.println(e);
        }
    }



    public static void forPractice() {
//        ArrayList<Integer> list = Lists.newArrayList(11, 33, 22, 66, 55, 88, 77);
//        for (int i = 0; i < list.size(); i++) {
//            if(i == 2){
//                Integer old = list.get(2);
//                list.remove(2);
//                Integer newVal = list.get(2);
//                System.out.println(old+"_"+newVal);
//            }
//        }
        ArrayList<Integer> descList = Lists.newArrayList(11, 33, 22, 66, 55, 88, 77);
        for (int i = descList.size() -1; i >=0 ; i--) {
            Integer old = descList.get(i);
            if(i==2){
                descList.remove(2);
                Integer newVal = descList.get(2);
                System.out.println(old+"_"+newVal);
            }else{
                System.out.println(old);
            }
        }



//        ArrayList<Integer> list2 = Lists.newArrayList(11, 33, 22, 66, 55, 88, 77);
//        for (Integer integer : list2) {
//            if(integer == 66){
//                list2.remove(integer);
//            }
//        }
//        System.out.println(JacksonUtil.serialize(list2));
    }

    private static void practice4() {
        //        21.对交易按照货币分组
        Map<Integer, List<Transaction>> collect = transactions.stream().collect(groupingBy(Transaction::getYear));
        System.out.println(JacksonUtil.serialize(collect));
        //        22.求出菜单列表的总热量,平均值等
        Integer collect1 = menu.stream().map(Dish::getCalories).collect(summingInt(a -> a));
        System.out.println(collect1);
        Double collect2 = menu.stream().map(Dish::getCalories).collect(averagingDouble(a -> a));
        System.out.println(collect2);
        IntSummaryStatistics collect3 = menu.stream().collect(summarizingInt(Dish::getCalories));
        long sum = collect3.getSum();
        double average = collect3.getAverage();
        System.out.println("sum:" + sum);
        System.out.println("average" + average);
        //        23.得到一个逗号分隔的菜肴名称列表
        String collect4 = menu.stream().map(Dish::getName).collect(joining(","));
        System.out.println(collect4);
        //        24.用reducing方法计算菜单的总热量
        Integer collect5 = menu.stream().collect(reducing(0, Dish::getCalories, Integer::sum));
        System.out.println(collect5);
        Integer reduce = menu.stream().map(Dish::getCalories).reduce(0, Integer::sum);
        System.out.println(reduce);
        //        25.用reduce方法实现  collector的toList方法
        ArrayList<Integer> intList = Lists.newArrayList(1, 2, 3, 4, 5, 6);
        List reduce1 = intList.stream().reduce(new ArrayList(), (List l, Integer a) -> {
            l.add(a);
            return l;
        }, (List l1, List l2) -> {
            l1.addAll(l2);
            return l1;
        });
        System.out.println(reduce1);
        //        26.把热量不到400卡路里的菜划分为“低热量”(diet),热量400到700卡路里的菜划为“普通”(normal),高于700卡路里的划为“高热量”(fat)
        Map<CaloricLevel, List<Dish>> collect6 = menu.stream().collect(groupingBy(dish -> {
            int calories = dish.getCalories();
            if (calories < 400) {
                return CaloricLevel.DIET;
            } else if (calories <= 700) {
                return CaloricLevel.NORMAL;
            } else {
                return CaloricLevel.FAT;
            }
        }));
        System.out.println(JacksonUtil.serialize(collect6));
        //                27.先按菜单中的类型分组,再按热量(低、中、高)分组
        Map<Dish.Type, Map<CaloricLevel, List<Dish>>> collect7 =
            menu.stream().collect(groupingBy(Dish::getType, groupingBy(dish -> {
                int calories = dish.getCalories();
                if (calories < 400) {
                    return CaloricLevel.DIET;
                } else if (calories <= 700) {
                    return CaloricLevel.NORMAL;
                } else {
                    return CaloricLevel.FAT;
                }
            })));
        System.out.println(JacksonUtil.serialize(collect7));
        //        28.计算菜单中每种类型的菜的数量
        Map<Dish.Type, Long> collect8 = menu.stream().collect(groupingBy(Dish::getType, counting()));
        System.out.println(JacksonUtil.serialize(collect8));
        //        29.查找每个类型中热量最高的菜
        Map<Dish.Type, Optional<Dish>> collect9 =
            menu.stream().collect(groupingBy(Dish::getType, maxBy(Comparator.comparingInt(Dish::getCalories))));
        System.out.println(collect9);
        //        30.求出每种类型的菜的热量和
        Map<Dish.Type, IntSummaryStatistics> collect10 =
            menu.stream().collect(groupingBy(Dish::getType, summarizingInt(Dish::getCalories)));
        System.out.println(JacksonUtil.serialize(collect10));
        //        31.查找每个子组中热量最高的 Dish
        Map<Dish.Type, Dish> collect11 = menu.stream().collect(groupingBy(Dish::getType,
            collectingAndThen(maxBy(Comparator.comparingInt(Dish::getCalories)), Optional::get)));
        System.out.println(collect11);
        //        32.把菜单按照素食和非素食分开
        Map<Boolean, List<Dish>> collect12 = menu.stream().collect(partitioningBy(Dish::isVegetarian));
        System.out.println(JacksonUtil.serialize(collect12));
        //        33.把菜单按照素食和非素食分开,再按菜的类型进行分组
        Map<Boolean, Map<Dish.Type, List<Dish>>> collect13 =
            menu.stream().collect(partitioningBy(Dish::isVegetarian, groupingBy(Dish::getType)));
        System.out.println(JacksonUtil.serialize(collect13));
        //        34.找到素食和非素食中热量最高的菜
        Map<Boolean, Object> collect14 = menu.stream().collect(partitioningBy(Dish::isVegetarian,
            collectingAndThen(maxBy(Comparator.comparingInt(Dish::getCalories)), Optional::get)));
        System.out.println(collect14);
        //        35.按菜的类型进行分组,并将菜名进行拼接
        Map<Dish.Type, String> collect15 =
            menu.stream().collect(groupingBy(Dish::getType, mapping(Dish::getName, joining(","))));
        System.out.println(JacksonUtil.serialize(collect15));
    }

    private static void notNullTest() {
        Person person = new Person();
        person.setName(null);
        //        @NonNull String name = person.getName();
        //        System.out.println(name);
    }

    static class Person {
        String name;

        public String getName() {
            return name;
        }

        public void setName(@NonNull String name) {
            this.name = name;
        }
    }

    private static void practice2() {
        //        10.找出2011年发生的所有交易,并按交易额排序(从低到高)
        List<Transaction> collect = transactions.stream().filter(x -> x.getYear() == 2011)
            .sorted(Comparator.comparingInt(Transaction::getValue)).collect(Collectors.toList());
        System.out.println(collect);
        //        11.交易员都在哪些不同的城市工作过?
        List<String> collect1 = transactions.stream().map(transaction -> transaction.getTrader().getCity()).distinct()
            .collect(Collectors.toList());
        System.out.println(collect1);
        //        12.查找所有来自于剑桥的交易员,并按姓名排序
        List<Trader> cambridge = transactions.stream().map(Transaction::getTrader)
            .filter(trader -> StringUtils.equals(trader.getCity(), "Cambridge"))
            .sorted(Comparator.comparing(Trader::getName)).collect(Collectors.toList());
        System.out.println(JacksonUtil.serialize(cambridge));
        //        13.返回所有交易员的姓名字符串,按字母顺序排序
        List<String> collect2 =
            transactions.stream().map(Transaction::getTrader).map(Trader::getName).sorted().distinct()
                .collect(Collectors.toList());
        System.out.println(collect2);
        //        14.有没有交易员是在米兰工作的?
        boolean milan = transactions.stream().map(Transaction::getTrader)
            .anyMatch(trader -> StringUtils.equals(trader.getCity(), "Milan"));
        System.out.println(milan);
        //                15.打印生活在剑桥的交易员的所有交易额
        List<Integer> collect3 = transactions.stream()
            .filter(transaction -> StringUtils.equals(transaction.getTrader().getCity(), "Cambridge"))
            .map(Transaction::getValue).sorted().collect(Collectors.toList());
        System.out.println(collect3);
        //        16.所有交易中,最高的交易额是多少?
        int value = transactions.stream().max(Comparator.comparingInt(Transaction::getValue)).get().getValue();
        System.out.println(value);
        Integer max = transactions.stream().map(Transaction::getValue).reduce(Integer::max).get();
        System.out.println(max);
        //                17.找到交易额最小的交易
        Transaction transaction = transactions.stream().min(Comparator.comparingInt(Transaction::getValue)).get();
        System.out.println(JacksonUtil.serialize(transaction));
        //        18.数值流计算菜单的总卡路里
        int sum = menu.stream().mapToInt(Dish::getCalories).sum();
        System.out.println(sum);
        //        19.数值流应用:勾股数
        List<double[]> collect4 = IntStream.rangeClosed(1, 10).boxed()
            .flatMap(a -> IntStream.rangeClosed(a, 10).boxed().map(b -> new double[] {a, b, Math.sqrt(a * a + b * b)}))
            .filter(doubles -> doubles[2] % 1 == 0).collect(toList());
        System.out.println(JacksonUtil.serialize(collect4));
        //        20.练习:斐波纳契元组序列
        //                (0, 1),(1, 1), (1, 2), (2, 3), (3, 5), (5, 8), (8, 13), (13, 21) ...
    }

    private static void practice3() {
        //        1.根据苹果的重量筛选,根据苹果的颜色筛选
        List<Apple> red = apples.stream().filter(apple -> StringUtils.equals(apple.getColor(), "red"))
            .filter(apple -> apple.getWeight() > 100).collect(Collectors.toList());
        System.out.println(JacksonUtil.serialize(red));
        //        2.在按重量比较两个苹果之后,你可能想要按原产国排序
        Stream<Apple> sorted = apples.stream().sorted(Comparator.comparingInt(Apple::getWeight).reversed())
            .sorted(Comparator.comparing(Apple::getColor).reversed());
        System.out.println(JacksonUtil.serialize(sorted));
        //        3. 一个苹果 既是红色,又重量大于150
        List<Apple> collect = apples.stream().filter(Apple::isRedApple).filter(apple -> apple.getWeight() > 100)
            .collect(Collectors.toList());
        System.out.println(JacksonUtil.serialize(collect));
        //        4.要么是重(150克以上)的红苹果,要么是绿苹果
        Predicate<Apple> isRedApple = apple -> StringUtils.equals(apple.getColor(), "red") && apple.getWeight() > 100;
        List<Apple> green =
            apples.stream().filter(isRedApple.or(apple -> StringUtils.equals(apple.getColor(), "green")))
                .collect(Collectors.toList());
        System.out.println(JacksonUtil.serialize(green));
        //        5.选出400卡路里以下的菜肴,按照卡路里排序,提取菜肴的名称,只选前3个,将所有名称保存在List中
        List<String> collect3 =
            menu.stream().filter(x -> x.getCalories() < 400).sorted(Comparator.comparingInt(Dish::getCalories))
                .map(Dish::getName).limit(3).collect(Collectors.toList());
        System.out.println(collect3);
        //        6.给定单词列表["Hello","World"] ,你想要返回列表 ["H","e","l", "o","W","r","d"]
        List<String> wordList = Lists.newArrayList("Hello", "World");
        List<String[]> collect1 = wordList.stream().map(word -> word.split("")).collect(Collectors.toList());
        System.out.println(JacksonUtil.serialize(collect1));
        List<String> collect2 =
            wordList.stream().map(word -> word.split("")).flatMap(Arrays::stream).collect(Collectors.toList());
        System.out.println(JacksonUtil.serialize(collect2));
        //        7.返回当前流中的任意元素
        Dish dish = menu.stream().findAny().get();
        System.out.println(JacksonUtil.serialize(dish));
        //        8.计算菜单中的总卡路里
        Integer collect4 = menu.stream().collect(summingInt(Dish::getCalories));
        System.out.println(collect4);
        int sum = menu.stream().mapToInt(Dish::getCalories).sum();
        System.out.println(sum);
        Integer integer = menu.stream().map(Dish::getCalories).reduce(Integer::sum).get();
        System.out.println(integer);
        Integer reduce = menu.stream().map(Dish::getCalories).reduce(0, (a, b) -> a + b);
        System.out.println(reduce);
        //        9.统计菜单中菜的个数
        long count = menu.stream().count();
        System.out.println(count);
        Integer integer1 = menu.stream().map(a -> 1).reduce(Integer::sum).get();
        System.out.println(integer1);
    }
}

文中示例代码均整理摘抄自《java8新特性实用》这本书

 

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值