Languages
[Edit]
EN

Java 8 - count unique String using Collectors.groupingBy

5 points
Created by:
Root-ssh
175500

Quick solution:

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class CountStrings {

    public static void main(String[] args) {

        List<String> usernames = new ArrayList<>();
        usernames.add("Kate"); // Kate - 1st time
        usernames.add("John");
        usernames.add("Ann");
        usernames.add("Kate"); // Kate - 2nd time
        usernames.add("Kate"); // Kate - 3rd time

        Map<String, Long> usersToCount = usernames.stream().collect(
                Collectors.groupingBy(
                        Function.identity(), Collectors.counting()
                )
        );

        usersToCount.forEach(
                (user, count) -> System.out.println(user + ", " + count)
        );
    }
}

Output:

Ann, 1
Kate, 3
John, 1

 

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Java 8 - stream API examples

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join