/** * @author lautturi.com * Java example: find the most common elements in map/hashmap */ import java.util.*; public class Lautturi { public static void main(String[] args) { ArrayList<String> string; string = new ArrayList<>(Arrays.asList("hello","JAVA","lautturi","java","python","world","lau","java","python","world","Java")); 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); } }
output:
{JAVA=4, LAU=1, HELLO=1, LAUTTURI=1, PYTHON=2, WORLD=2} maxEntry = JAVA