java - java中使用groupby()进行动态分组

标签 java collections group-by java-stream collectors

我正在研究一些场景。

用户选择一些列,然后对它们进行分组并显示。

我已经使用了标准,现在我想使用 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 ]
}

如何将属性Employeegetters映射并添加到分类器中?

或者他们有其他方式来分组这些属性吗?

最佳答案

您可以通过使用从属性名称到属性提取器的映射来完成此操作,即:

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/

相关文章:

android - JSON数据到android应用程序

mysql - 如何连接静态值并将它们用作 GROUP BY 标识符?

MySQL:如何查询列并在同一个表中包含来自相关列的信息?

java - toRightOf 在 Android 布局中未按预期工作

java - maven看不到本地安装的jar

java - 使用字符串指向某个列表(或数组)

python - 将 str 包含在另一行中的行分组

java - 如何单击其href在Selenium中具有某个子字符串的链接?

c# - 为了我们可以在其上放置 foreach,对集合的要求是什么?

node.js - Express js中用户登录时如何更新token?