Java Map
associates keys to values.
The keys in a Map must be unique, but the associated values need not be.
Three classes that implement interface Map are Hashtable, HashMap and TreeMap.
Hashtable and HashMap store elements in hash tables, and TreeMap store elements in trees.
Interface SortedMap extends Map and maintains its keys in sorted order.
Class TreeMap implements SortedMap.
Map Implementation with Hash Tables
The following code counts the number of occurrences of each word in a String.
import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.TreeSet; public class Main { public static void main(String[] args) { // create HashMap to store String keys and Integer values Map<String, Integer> map = new HashMap<>(); String input = "test a test this is is is is a test from demo2s.com"; String[] tokens = input.split(" "); for (String token : tokens) { String word = token.toLowerCase(); // get lowercase word // if the map contains the word if (map.containsKey(word)) // is word in map {/*from w ww .j a v a2 s . c om*/ int count = map.get(word); // get current count map.put(word, count + 1); // increment count } else map.put(word, 1); // add new word with a count of 1 to map } Set<String> keys = map.keySet(); // get keys // sort keys TreeSet<String> sortedKeys = new TreeSet<>(keys); System.out.printf("%nMap contains:%nKey\t\tValue%n"); // generate output for each key in map for (String key : sortedKeys) System.out.printf("%-10s%10s%n", key, map.get(key)); } }
import java.util.HashMap; import java.util.Map; public class Main { public static void main(String args[]) { Map<Integer, String> mils = new HashMap<>(); mils.put(1, "foo"); mils.put(2, "bar"); System.out.println("mils:\t" + mils); mils.put(1, "bar"); System.out.println("mils:\t" + mils); }// w w w . j av a 2 s . co m }