Java Collection How to - Create histogram from numbers








Question

We would like to know how to create histogram from numbers.

Answer

import java.util.HashMap;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;
public class Main {
    public static void main(String[] args) {
        Map<Integer,Integer> data = new HashMap<Integer,Integer>();
        data.put(10, 2);//  w w  w.  j  a  v a2s.c  o m
        data.put(20, 3);
        data.put(30, 5);
        data.put(40, 15);
        data.put(50, 4);

        SortedSet<Integer> keys = new TreeSet<Integer>(data.keySet());
        String s = "";
        for(Integer key : keys){
            s += key + " : ";
            for(int i = 0; i< data.get(key); i++){
                s+="*";
            }
            s+="\n";
        }
        System.out.println(s);
    }
}

The code above generates the following result.