Search code examples
javaarraysstringuniqueinstances

Java String Array max min unique occurrence


My input is a n number of strings . I want to get the unique values , as well as number of occurance of these string case insensitive.

I have a thought of getting the input in array ; sort it and do loops to calculate the occurance. Is there any other way?


Solution

  • You can use the Stream api facilities to get what you want:

    List<String> list = Arrays.asList("hello","world","Hola","Mundo","hello", "world","Hola","Mundo","mundo","Hello","Hola","mundo","Mundo");
    
    Map<String, Long> ocurrences = list
            .stream()
            .map(String::toLowerCase) // make case insensitive
            .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
    
    System.out.println(ocurrences);
    

    Output:

    {world=2, mundo=5, hello=3, hola=3}