JavaSE

2021-11-27 大约 2 分钟

# JavaSE

# Optional

public class OptionalDemo {

    public static void main(String[] args) {
        //创建Optional实例,也可以通过方法返回值得到。
        Optional<String> name = Optional.of("Sanaulla");

        //创建没有值的Optional实例,例如值为'null'
        Optional empty = Optional.ofNullable(null);

        //isPresent方法用来检查Optional实例是否有值。
        if (name.isPresent()) {
            //调用get()返回Optional值。
            System.out.println(name.get());
        }

        try {
            //在Optional实例上调用get()抛出NoSuchElementException。
            System.out.println(empty.get());
        } catch (NoSuchElementException ex) {
            System.out.println(ex.getMessage());
        }

        //ifPresent方法接受lambda表达式参数,如果Optional保存的值不为空,lambda表达式会接收这个值并处理
        name.ifPresent((value) -> {
            System.out.println("The length of the value is: " + value.length());
        });

        //返回保存的值或者提供的other的值
        System.out.println(empty.orElse("There is no value present!"));
        System.out.println(name.orElse("There is some value!"));

        //返回保存的值或者提供的lambda表达式参数的返回值
        System.out.println(empty.orElseGet(() -> "Default Value"));
        System.out.println(name.orElseGet(() -> "Default Value"));

        try {
            //抛出由传入的lambda表达式生成异常或者保存的值
            empty.orElseThrow(IllegalStateException::new);
        } catch (Throwable ex) {
            System.out.println(ex.getMessage());
        }

        //若Optonal值为null返回一个空的Optonal,否则通过传入的lambda表达式修改Optonal保值再包装成Optional返回。
        Optional<String> upperName = name.map((value) -> value.toUpperCase());
        System.out.println(upperName.orElse("No value found"));

        //同map如果lamdba直接返回Optional,不再包装
        upperName = name.flatMap((value) -> Optional.of(value.toUpperCase()));
        System.out.println(upperName.orElse("No value found"));

        //如果满足返回Optional实例值,否则返回空Optional。
        Optional<String> longName = name.filter((value) -> value.length() > 6);
        System.out.println(longName.orElse("The name is less than 6 characters"));
    }
}
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

# Stream

使用如下实体类

public class Employee {
    private int id;
    private String sex;
    private int age;
    private String city;
    private Double sale;
}
1
2
3
4
5
6
7
  • groupingBy

public class StreamTest() {
    @Test
    public void groupingByTest() {
        // 按城市分组list
        Map<String, List<Employee>> employeesByCity =
                employees.stream().collect(Collectors.groupingBy(Employee::getCity));
        
        // 统计每组员工个数
        Map<String, Long> employeesByCity =
                employees.stream().collect(Collectors.groupingBy(Employee::getCity, Collectors.counting()));
        
        // 统计每组工资平均
        Map<String, Double> employeesByCity =
                employees.stream().collect(Collectors.groupingBy(Employee::getCity, Collectors.averagingInt(Employee::getSales)));
        // 统计每组总工资
        Map<String, Double> employeesByCity =
                employees.stream().collect(Collectors.groupingBy(Employee::getCity, Collectors.summingLong(Employee::getSales)));
        
        // 将每组对象提取其中一个属性
        Map<String, List<String>> namesByCity =
                employees.stream().collect(Collectors.groupingBy(Employee::getCity, Collectors.mapping(Employee::getName, Collectors.toList())));
        
        // 对一个属性进行文字join
        Map<Integer, String> postsPerType = employees.stream()
                .collect(Collectors.groupingBy(Employee::getCity,
                        Collectors.mapping(Employee::getName, Collectors.joining(", ", "Post titles: [", "]"))));
    }
}


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
上次编辑于: 2022年9月20日 12:18