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;
}
}
如何在java 8中使用groupBy然后进行求和和排序
这是我的数据
Emp("Michael", "Sales",20000.0)
Emp("Jean","Marketing",250000.0)
Emp("Jason","Biz-dev",220000.0)
..........
答案 0 :(得分:3)
薪资总额排名前5位的部门:
set_time_limit(0);
$array = array('1','2', '3');
foreach ($array as $row) {
echo $row . '<br>';
sleep(50);
}
特定部门的薪水前5名员工:
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());
答案 1 :(得分:1)
我想过直接放入支持按值排序的Map
。这样的事情在jdk中不存在,但在guava
例如。所以你的解决方案可能看起来像这样:
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);
这不是更好然后已经提供的解决方案,它只是可以这样做的事情。