按数组列表分组 [英] groupingby list of arrays

查看:81
本文介绍了按数组列表分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到了需要分组的对象数组的列表.数组包含不同类型的对象. 这是一个示例:

I get a list of object arrays that I need to group. The arrays contain different types of objects. Here is an example:

List<Object[]> resultList = query.getResultList(); // call to DB

// Let's say the object array contains objects of type Student and Book
// and Student has a property Course.
// Now I want to group this list by Student.getCourse()
Map<String, Object[]> resultMap = resultList.stream().collect(Collectors.groupingBy(???));

我可以为Collectors.groupingBy()方法提供什么? Student对象位于对象数组的索引0处.

What do I provide to the Collectors.groupingBy() method ? The Student object is at index 0 in the object array.

推荐答案

groupingBy在默认情况下会为您提供Map<String, List<Object[]>>,因为您将根据学生的课程价值对数组进行分组.

groupingBy will by default give you a Map<String, List<Object[]>> in your case, because you will group arrays based on their student's course value.

因此,您需要按数组中学生的课程值进行分组.因此,您将应用的功能将是:

So you need to group by the course value of the student in the array. The function you will apply will hence be:

o -> ((Student)o[0]).getCourse()

因此,按实现分组的内容为:

thus the grouping by implementation becomes:

Map<String, List<Object[]>> resultMap = 
    resultList.stream().collect(groupingBy(o -> ((Student)o[0]).getCourse()));

顺便说一句,您可能希望使用一个类来键入数据并避免进行强制转换,否则可能会在运行时引发异常.

As an aside, you may want to use a class to have typed data and to avoid the cast, that could possibly throw an exception at runtime.

您还可以在数据库级别执行分组.

You could also perform the grouping by at the database level.

这篇关于按数组列表分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆