Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save kayode-adechinan/13cc45a91f01bc7f34f50a2aa9fa69c9 to your computer and use it in GitHub Desktop.
Save kayode-adechinan/13cc45a91f01bc7f34f50a2aa9fa69c9 to your computer and use it in GitHub Desktop.
Java 8 One liners for statistical properties : Mean, Mode, Median(Q2), Q1, Q2, Variance, Standard Deviation

While working on a Hacker Rank Problem I wrote few one lines using java stream to find mean, median, mode, Q1, Q3, variance and standard deviation. Thought to share since it's quite interesting.

        // mean
        double mean = list.stream().mapToInt(Integer::intValue).average().getAsDouble();
        System.out.println(mean);
        
        // mode - create count map using group by and sorted with custom comparator to give minimum from competing probable mode values
        Integer mode = list.stream()
                .collect(Collectors.groupingBy(i -> i, () -> new TreeMap<Integer, Long>(), Collectors.counting()))
                .entrySet().stream().sorted((a, b) -> {
                    if (!a.getValue().equals(b.getValue()))
                        return b.getValue().compareTo(a.getValue());
                    return a.getKey().compareTo(b.getKey());
                }).findFirst().get().getKey();
        System.out.println(mode);
        
        // Q1
        double q1 = list.stream().sorted().skip(Math.max(0, ((list.size() / 2 + 1) / 2) - 1))
                .limit(1 + (1 + list.size() / 2) % 2).mapToInt(Integer::intValue).average().getAsDouble();
        System.out.println(q1);

        // median (Q2)
        double median = list.stream().sorted().skip(Math.max(0, ((list.size() + 1) / 2) - 1))
                .limit(1 + (1 + list.size()) % 2).mapToInt(Integer::intValue).average().getAsDouble();
        System.out.println(mean);
       
        // Q3
        double q3 = list.stream().sorted()
                .skip(Math.max(0, ((list.size() + 1) / 2) ))
                .skip(Math.max(0, ((list.size() / 2 + 1) / 2) - 1))
                .limit(1 + (1 + list.size() / 2) % 2)
                .mapToInt(Integer::intValue).average().orElse(list.get(0));
        System.out.println(q3);

        // Variance
        double variance = list.stream()
                              .map(i -> i - mean)
                              .map(i -> i*i)
                              .mapToDouble(i -> i).average().getAsDouble();
        System.out.println(variance);
        
        //Standard Deviation 
        double standardDeviation = Math.sqrt(variance);
        System.out.println(standardDeviation);
         
        // If number required to printed with specific rounding
        System.out.println(BigDecimal.valueOf(Math.sqrt(standardDeviation)).setScale(4, BigDecimal.ROUND_HALF_UP).toPlainString());

Video: Mean, Median, and Mode

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment