我正在研究一些场景。
用户选择一些列,然后对它们进行分组并显示。
我已经使用了标准,现在我想使用 java groupby() 进行分组。
假设我有一个实体 Employee:
package com.demo;
public class Employee {
int id;
String name;
String address;
String phoneno;
String designation;
public Employee(int id, String name, String address, String phoneno, String designation) {
super();
this.id = id;
this.name = name;
this.address = address;
this.phoneno = phoneno;
this.designation = designation;
}
}
// getter and setters
我创建了另一个用于分组的类
public class GroupHere {
public static void main(String arg[]) {
Function<Employee, List<Object>> classifier = (emp) ->
Arrays.<Object>asList(emp.getAddress(),emp.getName());
Map<Employee, Long> groupedEmployee = employee.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println("key" + groupedEmployee .keySet());
System.out.println("Grouped by" + groupedEmployee );
}
}
现在我想动态创建分类器,以便当用户选择“name”和“phoneno”时 分类器中应该有这些 setter/getter 。
我在这里很困惑。
此外,当用户选择详细信息采用 JSON 格式的属性/列时。
{
[ attributes: name, groupable: true ],
[ attributes: phoneno, groupable: true ]
}
如何将属性与Employee的getters映射并添加到分类器中?
或者他们有其他方式来分组这些属性吗?
最佳答案
您可以通过使用从属性名称到属性提取器的映射来完成此操作,即:
Map<String, Function<Employee, Object>> extractors = new HashMap<>();
extractors.put("name", Employee::getName);
extractors.put("address", Employee::getAddress);
extractors.put("phoneno", Employee::getPhoneno);
extractors.put("designation", Employee::getDesignation);
获得此映射后,您可以使用它动态创建分类器:
List<String> attributes = ...; // get attributes from JSON (left as exercise)
Function<Employee, List<Object>> classifier = emp -> attributes.stream()
.map(attr -> extractors.get(attr).apply(emp))
.collect(Collectors.toList());
现在,您可以使用此分类器对员工进行分组:
Map<List<Object>, Long> groupedEmployees = employees.stream()
.collect(Collectors.groupingBy(classifier, Collectors.counting()));
关于java - java中使用groupby()进行动态分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64159520/