• Java基础(二十)Stream练习


    Stream练习

    1. 拼接

    给定一个字符串数组,使用 Stream 把所有字符串拼接成一个字符串。

    import java.util.Arrays;
    import java.util.stream.Collectors;
    
    public class StringJoinWork01 {
        public static void main(String[] args) {
            String[] arr = {"a", "b", "c"};
            System.out.println(Arrays.stream(arr).collect(Collectors.joining()));  // abc
            System.out.println(String.join("",arr));  // abc
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    2. 求值

    有一个整数集合,分别完成以下操作:

    • 所有元素之和
    • 最大值
    • 最小值
    import java.util.Arrays;
    import java.util.OptionalInt;
    
    public class EvaluationWork02 {
        public static void main(String[] args) {
            int[] ints = {2, 3, 4, 5, 10, 2, 1};
    
            long count = Arrays.stream(ints).count();  // 计数
            System.out.println(count);  // 7
            OptionalInt max = Arrays.stream(ints).max();  // 最大值
            System.out.println(max.getAsInt());  // 10
            OptionalInt min = Arrays.stream(ints).min();  // 最小值
            System.out.println(min.getAsInt());  // 1
            int sum = Arrays.stream(ints).sum();  // 求和
            System.out.println(sum);  // 27
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    3. 薪资最低的员工

    有一个员工类Employee,里面有name、age和salary字段。请通过 Stream 对多个Employee对象按salary排序,然后取前3个输出。

    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Comparator;
    
    public class SalaryMinWork03 {
        public static void main(String[] args) {
            ArrayList<Employee> employees = new ArrayList<>();
    
            employees.add(new Employee("小羊呆呆", 18, 5200.0));
            employees.add(new Employee("张三", 25, 6000.0));
            employees.add(new Employee("李四", 30, 8000.0));
            employees.add(new Employee("王五", 22, 4500.0));
            employees.add(new Employee("赵六", 28, 7000.0));
    
            /**
             * 方法一
             */
            // 排序
            employees.sort((user,user1) -> (int) (user.getSalary()-user1.getSalary()));
            // 翻转
            Collections.reverse(employees);
            // 取前3,输出
            employees.stream().limit(3).forEach(System.out::println);
    
            /**
             * 方法二
             */
            employees.stream()
                    .sorted(new Comparator<Employee>() {
                        @Override
                        public int compare(Employee o1, Employee o2) {
                            return (int)((o1.getSalary() - o2.getSalary()) * -1);
                        }
                    })
                    .limit(3)
                    .forEach(s -> System.out.println(s));
    
            /**
             * 方案三:优雅!!!
             */
            employees.stream()
                    .sorted(Comparator.comparingDouble(Employee::getSalary).reversed())
                    .limit(3)
                    .forEach(System.out::println);
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47

    4. 平均值

    有一个整数集合,求每个元素平方的平均值。

    int[] ints = {2, 3, 4, 5, 10, 2, 1};
    DoubleStream aDouble = Arrays.stream(ints).mapToDouble(i -> Math.pow(i, 2));
    // System.out.println(Arrays.toString(aDouble.toArray()));  // [4.0, 9.0, 16.0, 25.0, 100.0, 4.0, 1.0]
    System.out.println(aDouble.average().getAsDouble());  // 22.714285714285715
    
    • 1
    • 2
    • 3
    • 4

    集合练习

    1. 斗地主

    有一个集合保存扑克牌的花色(四种),另一个集合保存扑克牌点数(13个)。创建一个新的集合保存所有的扑克牌(54张,包含 大小王)。将扑克牌分为四份(3个玩家,1份底牌),排序后输出四份手牌。

    import java.util.*;
    
    public class PlayingCardsWork021 {
        public static void main(String[] args) {
            List<String> suits = Arrays.asList("♠", "♥", "♦", "♣");  // 花色
            List<String> ranks = Arrays.asList("2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A", "小王", "大王");  // 点数
            List<String> deck = new ArrayList<>();  // 扑克牌
            // 向扑克牌列表中储存元素
            for (String suit : suits) {
                for (String rank : ranks.subList(0, 13)) {
                    String card = suit + rank;
                    deck.add(card);
                }
            }
            deck.add("大王");
            deck.add("小王");
    
            List<String> player1 = new ArrayList<>(); // 玩家一
            List<String> player2 = new ArrayList<>(); // 玩家二
            List<String> player3 = new ArrayList<>(); // 玩家三
    
            shuffle(deck);  // 洗牌
    
            /**
             * 发牌
             */
            for (int i = 0; i < deck.size() - 3; i++) {
                switch (i % 3) {
                    case 0 -> player1.add(deck.get(i));
                    case 1 -> player2.add(deck.get(i));
                    case 2 -> player3.add(deck.get(i));
                }
            }
            // 底牌
    //        for (int i = 1; i < 4; i++) {
    //            bottom.add(deck.get(deck.size() - i));
    //        }
    //        Collections.reverse(bottom);  // 翻转,使底牌顺序正确
            // 底牌
            List<String> bottom = new ArrayList<>(deck.subList(51, 54));
    
            // 定义比较器
            Comparator<String> cardComparator = (o1, o2) -> {
                int indexColor = suits.indexOf(o1.substring(0,1)) -suits.indexOf(o2.substring(0,1));  // 比较花色
                o1 = o1.replaceAll("[♠♥♦♣]", "");  // String 是不可变类型,对它进行增删改查相当于新new一个String对象
                o2 = o2.replaceAll("[♠♥♦♣]", "");
                int inCompate = (ranks.indexOf(o1) - ranks.indexOf(o2)) * -1;  // 比较数字
                return inCompate != 0? inCompate : indexColor;
            };
            // 排序,整理手牌
            player1.sort(cardComparator);
            player2.sort(cardComparator);
            player3.sort(cardComparator);
    
            // 展示
            System.out.println("玩家1\t" + player1);
            System.out.println("玩家2\t" + player2);
            System.out.println("玩家3\t" + player3);
            System.out.println("底牌 \t" + bottom);
            System.out.println(deck);
        }
    
        /**
         * 洗牌
         * @param list
         */
        public static void shuffle(List<String> list) {
            for (int i = 0; i < 3; i++) {
                // System.currentTimeMillis() 来设置随机种子。每一次运行程序时都会使用不同的随机种子,从而产生更随机的结果。
                Collections.shuffle(list, new Random(System.currentTimeMillis()));
            }
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74

    2. 生日提醒

    编写一个生日提醒程序,使用Map来存储人名和对应的生日日期。够根据日期提醒用户哪些人今天过生日?

    • 如何筛选显示出最近七天过生日的用户
    import java.time.LocalDate;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.Map;
    
    public class BirthdayReminderWork022 {
        public static void main(String[] args) {
            HashMap<String, LocalDate> brith = new HashMap<>();
    
            // 添加人员的生日信息
            brith.put("张三", LocalDate.of(1990, 5, 20)); // 假设生日为1990年6月20日
            brith.put("李四", LocalDate.of(1988, 9, 10)); // 假设生日为1988年9月10日
            brith.put("王五", LocalDate.of(1995, 2, 15)); // 假设生日为1995年3月15日
    
            System.out.println(brith);
    
            Iterator<Map.Entry<String, LocalDate>> iterator = brith.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, LocalDate> next = iterator.next();
                int day = next.getValue().getDayOfMonth() - LocalDate.now().getDayOfMonth();
                boolean isBrith = next.getValue().getMonth().equals(LocalDate.now().getMonth())
                        && day <= 7;
                if (isBrith) {
                    System.out.printf("距离%s生日还有%d天\n", next.getKey(), day);
                }
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
  • 相关阅读:
    如何发布离线地图服务及二次开发API
    【电路笔记】-电流源
    SpringCloud
    2月21日,每日信息差
    赛事重启!第五届“强网”拟态防御国际精英挑战赛重磅归来!
    lambda表达式
    【ArcGIS教程】批量裁剪-创建模型
    基于http-flv的抖音直播端到端延迟优化实践
    损失函数中的均方误差以及平方误差
    CS5266BN说明书|CS5266BN QFN48封装规格书|CS5266BN设计资料
  • 原文地址:https://blog.csdn.net/bao_14440/article/details/132744743