import java.util.*; public class TestArgsWords { private static final Integer ONE = new Integer(1); public static void main(String[] args) { Map<String, Integer> m = new HashMap<>(); for (int i = 0; i < args.length; i++) { Integer freq = m.get(args[i]); m.put(args[i], freq == null ? ONE : new Integer(freq.intValue() + 1)); } System.out.println( m.size() + " distinct words detected:"); System.out.println(m); } }
或者利用 auto_boxing / auto_unboxing 機制寫成:java
import java.util.*; public class TestArgsWords { private static final int ONE = 1; public static void main(String[] args) { Map<String, Integer> m = new HashMap<>(); for (int i = 0; i < args.length; i++) { int freq = m.get(args[i]) == null ? 0 : m.get(args[i]); m.put(args[i], freq == 0 ? ONE : freq + 1); } System.out.println( m.size() + " distinct words detected:"); System.out.println(m); } }
運行結果:3d