Raj Hassani
Raj Hassani

Reputation: 1677

How to use groupby/Lambda

public class Emp {

    public String name;
    public String department;
    public double salary;

    public Emp(String name, String department, double salary) {

        this.name = name;
        this.department = department;
        this.salary = salary;
    }
}
  1. So I am trying to get top 5 departments by summing salaries and
  2. Also trying to top 5 employees in a department say sales

How do I use groupBy in java 8 and then summing and sorting

This is the data I have

Emp("Michael", "Sales",20000.0) Emp("Jean","Marketing",250000.0) Emp("Jason","Biz-dev",220000.0) ..........

Upvotes: 0

Views: 688

Answers (2)

Eugene
Eugene

Reputation: 120858

I thought about putting directly into a Map that supports order by values. Such a thing does not exist in jdk, but does in guava for example. So your solution could look like this:

 Map<String, Double> map = employees.stream().collect(
            Collectors.collectingAndThen(Collectors.groupingBy(Emp::getDepartment,
                    Collectors.summingDouble(Emp::getSalary)),
                    x -> ImmutableMap.<String, Double> builder()
                            .putAll(x)
                            .orderEntriesByValue(Comparator.comparing((Double d) -> d).reversed())
                            .build()));

    map.entrySet().stream().map(Map.Entry::getValue).limit(5).forEach(System.out::println);

This is not better then the solution already provided, it's just something that could be done like this.

Upvotes: 1

castletheperson
castletheperson

Reputation: 33486

Top 5 departments by total of salaries:

List<String> top5Departments = employees.stream()
    .collect(Collectors.groupingBy(e -> e.department,
                 Collectors.summingDouble(e -> e.salary)))
    .entrySet()
    .stream()
    .sorted(Map.Entry.comparingByValue().reversed())
    .limit(5)
    .map(Map.Entry::getKey)
    .collect(Collectors.toList());

Top 5 employees by salary in a specific department:

List<Emp> top5SalesEmployees = employees.stream()
    .filter(e -> "sales".equals(e.department))
    .sorted(Comparator.comparingDouble(e -> e.salary).reversed())
    .limit(5)
    .collect(Collectors.toList());

Upvotes: 3

Related Questions