0

I've got names in an ArrayList , and I would like to find the most common element in the simplest way. I tried to use Collectoins.max() , but it's return value was incorrect.

I created a HashMap, using names az Keys and quantity of names as Values, but I couldn't figure out how to write the names with the highest values.

( Actually, if there is two or more names with highest values, I have to get all of them. )

jaraipali
  • 41
  • 2
  • 8
  • Maybe we are talking **Collections.frequency(Collection> c, Object o)** here? Most common element is closely related to **frequency** instead of max?? – ShayHaned Jun 30 '17 at 09:13

1 Answers1

1
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class StringChecker {

public static void main(String[] args) {
    ArrayList<String> string;
    string = new ArrayList<>(Arrays.asList("Mah", "Bob", "mah", "bat", "MAh", "BOb"));
    Map<String, Integer> wordMap = new HashMap<String, Integer>();

    for (String st : string) {
        String input = st.toUpperCase();
        if (wordMap.get(input) != null) {
            Integer count = wordMap.get(input) + 1;
            wordMap.put(input, count);
        } else {
            wordMap.put(input, 1);
        }
    }
    System.out.println(wordMap);
    Object maxEntry = Collections.max(wordMap.entrySet(), Map.Entry.comparingByValue()).getKey();
    System.out.println("maxEntry = " + maxEntry);
}

}

Mahesh Kshirsagar
  • 390
  • 1
  • 3
  • 12