17. TreeMap and TreeSet
TreeSet
TreeSet<Integer> schedule = new TreeSet<Integer>();
schedule.add(1223);
schedule.add(1430);
schedule.add(1545);
schedule.add(1610);
schedule.add(1705);
schedule.add(2010);
schedule.add(2215);
schedule.add(2320);
schedule.add(2345);
System.out.println(schedule.headSet(1600).last());
System.out.println(schedule.tailSet(2200).first());
TreeMap
Map<String, Integer> freqOfWords = new HashMap<String, Integer>();
String[] words = "coming together is a beginning keeping together is progress working together is success"
.split(" ");
for (String word : words) {
Integer frequency = freqOfWords.get(word);
if (frequency == null) {
frequency = 1;
} else {
frequency++;
}
freqOfWords.put(word, frequency);
}
System.out.println("Elements in HashMap: " + freqOfWords);
TreeMap<String, Integer> sortedWords = new TreeMap<String, Integer>(freqOfWords);
Back to Home
Next Lecture