Created
November 20, 2013 05:48
-
-
Save hoffrocket/7558352 to your computer and use it in GitHub Desktop.
Java 8 Histogram
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Map; | |
import java.util.Random; | |
import java.util.function.Function; | |
import java.util.stream.Collectors; | |
import java.util.stream.Stream; | |
public class Histogram { | |
public static <T> Map<T, Integer> histogram(Stream<T> stream) { | |
return stream.collect( | |
Collectors.groupingBy(Function.<T>identity(), | |
Collectors.mapping(i -> 1, Collectors.summingInt(s -> s.intValue())))); | |
} | |
public static void main(String [] a) { | |
Map<Integer, Integer> histo = histogram(new Random().ints(1, 11).limit(10000).boxed()); | |
System.out.println(histo); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This will not be very useful with floating point numbers. And it does not allow to set the bin width, so it makes an histogram of bin of width 1. A little bit of more code you can get something more useful.
`
import java.util.;
import java.util.stream.;
/**
*/
public class Histogram{
private int nBins, N=0;
private double min = Double.POSITIVE_INFINITY , max = Double.NEGATIVE_INFINITY;;
private double binWidth;
public Histogram(){
}