1

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?

4
  • How does your input (<i>n number of strings</i>) look like? Is it an array, a list or a map? Or anything else? Commented Oct 10, 2017 at 14:25
  • 3
    Map strings to numbers of occurrences. Commented Oct 10, 2017 at 14:26
  • it is an array of strings Commented Oct 10, 2017 at 14:32
  • book;glass;phone;watch;mobile;ink;pen;watch;glass; Commented Oct 10, 2017 at 14:34

2 Answers 2

2

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}

Sign up to request clarification or add additional context in comments.

Comments

1
public Map<String, Integer> calculateOccurences(Collection<String> collectionOfStrings) {
        HashMap<String, Integer> map = new HashMap<String, Integer>();
        for (String string : collectionOfStrings) {
            String stringAsLowerCase = string.toLowerCase();
            Integer integer = map.get(stringAsLowerCase);
            if (integer == null) { //this has never been added
                map.put(stringAsLowerCase, 1);
            } else {
                map.put(stringAsLowerCase, integer + 1);
            }
        }
        return map;
    }

This will return a map where the keys are the unique words and each value will tell you how many times it appeared.

1 Comment

Use Integer integer = map.getOrDefault(stringAsLowerCase, 0); then you can get rid of the conditional logic

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.