Read file content and save to a TreeMap : TreeMap « Collections Data Structure « Java

Read file content and save to a TreeMap


import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;

public class LogTest {
  public static void main(String[] args) throws IOException {
    String inputfile = args[0];
    String outputfile = args[1];

    Map<String, Integer> map = new TreeMap<String, Integer>();

    Scanner scanner = new Scanner(new File(inputfile));
    while (scanner.hasNext()) {
      String word =;
      Integer count = map.get(word);
      count = (count == null ? 1 : count + 1);
      map.put(word, count);

    List<String> keys = new ArrayList<String>(map.keySet());
    Collections.sort( keys );

    PrintWriter out = new PrintWriter(new FileWriter(outputfile));
    for (String key : keys)
      out.println(key + " : " + map.get(key));


Related examples in the same category

2.Get Synchronized Map from Java TreeMap
3.Check if a particular key exists in Java TreeMap
4.Get Set view of Keys from Java TreeMap
5.Get Tail Map from Java TreeMap
6.Get Size of Java TreeMap
7.Remove value from Java TreeMap
8.Iterate through the values of Java TreeMap
9.Check if a particular value exists in Java TreeMap
10.Remove all values from Java TreeMap
11.Get Sub Map from Java TreeMap
12.Get lowest and highest key stored in Java TreeMap
13.Get Head Map from Java TreeMap
14.Use Generic TreeMap to store Integer as key and String as value