大佬教程收集整理的这篇文章主要介绍了使用Collection.stream按特定属性动态分组,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
使代码更具动态性的主要问题是,您事先不知道要分组多少个元素。在这种情况下,最好对List
所有元素进行分组。之所以可行,是因为如果两个列表的所有元素均相同且顺序相同,则它们相等。
在这种情况下,我们将按照由每种数据类型和模块组成的列表进行分组,而不是按类型和模块进行分组。
private static Map<List<String>, List<MyClass>> groupListBy(List<MyClass> data, String[] groupByFIEldnames) {
final MethodHandles.Lookup lookup = MethodHandles.lookup();
List<MethodHandle> handles =
Arrays.stream(groupByFIEldnames)
.map(fIEld -> {
try {
return lookup.findGetter(MyClass.class, fIEld, String.class);
} catch (Exception E) {
throw new RuntimeException(E);
}
}).collect(toList());
return data.stream().collect(grouPingBy(
d -> handles.stream()
.map(handle -> {
try {
return (String) handle.invokeExact(d);
} catch (Throwable E) {
throw new RuntimeException(E);
}
}).collect(toList())
));
}
代码的第一部分将字段名称数组转换为List
的@H_448_3@methodHandle。对于每个字段,将@H_448_3@methodHandle为该字段检索a
:这是通过从中获取查询@H_448_3@methodHandles.lookup()并使用来查找给定字段名称的句柄来完成的findGetter
:
其余代码创建分类器,以将其分组。在数据实例上调用所有句柄以返回String
值列表。这Stream
被收集到List
作为分类器。
样例代码:
public static voID main(String[] args) {
List<MyClass> data = new ArrayList<>();
data.add(new MyClass("1", "A", "B"));
data.add(new MyClass("2", "A", "B"));
data.add(new MyClass("3", "A", "C"));
data.add(new MyClass("4", "B", "A"));
System.out.println(groupListBy(data, new String[] { "type", "module" }));
}
输出:
{[B, A]=[4], [A, B]=[1, 2], [A, C]=[3]}
@H_448_3@myClass.toString()重写when 返回@R_674_10283@e
唯一的。
我正在尝试使用Java 8 Collection-Stream按多个属性对对象列表进行分组。
效果很好:
public class MyClass
{
public String @R_674_10283@e;
public String type;
public String module;
public MyClass(String @R_674_10283@e,String type,String modulE)
{
this.type = type;
this.@R_674_10283@e = @R_674_10283@e;
this.module= module;
}
}
List<MyClass> data = new ArrayList();
data.add(new MyClass("1","A","B"));
data.add(new MyClass("2","B"));
data.add(new MyClass("3","C"));
data.add(new MyClass("4","B","A"));
Object result = data.stream().collect(Collectors.groupingBy((MyClass m)
-> m.type,Collectors.groupingBy((MyClass m) -> m.modulE)));
但我想使其更具动态性。我只想指定一个应该用于GroupBy的字符串数组(或列表)。
就像是:
Object groupListBy(List data,String[] groupByFieldNames)
{
//magic code
}
我想打电话给:
groupListBy(data,new String[]{"type","module"});
像我的示例一样,如何使groupBy-Method更动态?
以上是大佬教程为你收集整理的使用Collection.stream按特定属性动态分组全部内容,希望文章能够帮你解决使用Collection.stream按特定属性动态分组所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。