Performing multiple logical operations in a thread

Trying to release java 8 threads. Is it possible in threads to find the number of elements starting with X, Y, Z, from a list that contains many elements.

transactions.stream()
            .filter(e -> startsWith("X"))
            .count();

transactions.stream()
            .filter(e -> startsWith("Y"))
            .count();

transactions.stream()
            .filter(e -> startsWith("Z"))
            .count();

The above code indicates the number of elements starting with X, Y, Z in the list, but in the above case I repeat three times to get the data. This can be done by looping through the list only once, using a simple loop. Is it possible to fulfill all these conditions in one thread (iterate only once) instead of using multiple threads?

Any help is greatly appreciated.

+4
source share
2 answers

. , :

Map<String, Long> collect = transactions.stream().collect(Collectors.groupingBy(t -> {
    if (t.startsWith("X")) {
        return "X";
    }
    if (t.startsWith("Y")) {
        return "Y";
    }
    if (t.startsWith("Z")) {
        return "Z";
    }
    return "none";
}, Collectors.counting()));

-

{X=1, Y=1, Z=1, none=1}

+10

, .

Map<String, Long> collect = transactions.stream()
                                        .collect(Collectors.groupingBy(s -> s.substring(0, 1), Collectors.counting()))

"X", "Y", "Z", "a", "c" , .

, get, , , :

collect.get("X");
collect.get("Y");
collect.get("Z");
0

Source: https://habr.com/ru/post/1677873/