【问题标题】:Dynamic Grouping using groupby() in java在 java 中使用 groupby() 进行动态分组
【发布时间】:2021-01-17 10:06:00
【问题描述】:

我正在处理一些场景。

用户选择一些列并对其进行分组并显示出来。

我已经完成了使用条件,现在我想使用 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 );

   }
}
        

现在我想动态创建我的分类器,以便当用户选择“姓名”和“电话号码”时 分类器中应该包含这些 getter。

我在这里很困惑。

当用户选择详细信息在 JSON 中的属性/列时。

{
 [ attributes: name, groupable: true ],
 [ attributes: phoneno, groupable: true ]
}

如何将 attributesEmployeegetter 映射并添加到 classifier 中?

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

【问题讨论】:

标签: java collections group-by java-stream collectors


【解决方案1】:

您可以通过使用从属性名称到属性提取器的映射来做到这一点,即:

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()));

【讨论】:

    猜你喜欢
    • 2013-01-23
    • 2019-06-30
    • 2020-01-01
    • 2021-11-22
    • 2022-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-07
    相关资源
    最近更新 更多