Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

This java steam does not return the correct value

Tags:

java

steam

I want to return the age group, or zero if there is no age, but the hashMap key simply does not show the age 21-23 when there is no age

List<Person> users = Arrays.asList(
    new Person(18, "张三", "123", 1),
    new Person(19, "李四", "124", 0),
    new Person(20, "王五", "125", 1),
    new Person(24, "孙八", "128", 0),
    new Person(27, "周九", "129", 1)
); 
Map<String, Long> group2 = users.stream()
    .collect(Collectors.groupingBy(u -> {
            int age = u.getAge();
            if (age >= 18 && age <= 20) { 
                return "18-20"; 
            } else if (age >= 21 && age <= 23) { 
                return "21-23"; 
            } else if (age >= 24 && age <= 26) {
                return "24-26"; 
            } else {
                 return "else"; 
            }
        }), Collectors.counting());
like image 592
johnson Avatar asked Sep 20 '26 00:09

johnson


1 Answers

You can make default supplier that returns 0 if the group is empty.

List<Person> users = Arrays.asList(
    new Person(18, "张三", "123", 1),
    new Person(19, "李四", "124", 0),
    new Person(20, "王五", "125", 1),
    new Person(24, "孙八", "128", 0),
    new Person(27, "周九", "129", 1)
); 

// Create a default Map with all possible age groups and a count of zero for each age group
Supplier<Map<String, Long>> defaultMapSupplier = () -> Stream.of("18-20", "21-23", "24-26", "else")
        .collect(Collectors.toMap(ageGroup -> ageGroup, ageGroup -> 0L));

Map<String, Long> ageCountMap = users.stream()
    .collect(Collectors.groupingBy(
            u -> {
                int age = u.getAge();
                if (age >= 18 && age <= 20) { return "18-20"; }
                else if (age >= 21 && age <= 23) { return "21-23"; }
                else if (age >= 24 && age <= 26) { return "24-26"; }
                else { return "else"; }
            },
            defaultMapSupplier,
            Collectors.counting()
    ));
like image 89
Broccoli_Salad Avatar answered Sep 21 '26 14:09

Broccoli_Salad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!