Get word frequency in a sentence
import java.text.DecimalFormat; import java.util.LinkedHashMap; import java.util.Map; public class Main { public static void main(String[] args) { String[] cards = "a b d e".split("\\W+"); Map<String,Integer> frequences = new LinkedHashMap<>(); for (String card : cards) { if(frequences.containsKey(card)){ frequences.put(card,frequences.get(card) + 1); } else { frequences.put(card,1);//from w w w .jav a 2s. c om } } DecimalFormat formatter = new DecimalFormat("#0.00"); for (Map.Entry<String,Integer> face : frequences.entrySet()) { System.out.println(face.getKey() + " -> " + formatter.format((double)face.getValue() * 100 / cards.length) + "%"); } } }