按分组列表排列
问题描述:
我得到了需要分组的对象数组列表。数组包含不同类型的对象。 下面是一个例子:按分组列表排列
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处。
答
groupingBy
默认情况下会给你一个Map<String, List<Object[]>>
你的情况,因为你会根据他们学生的课程价值对数组进行分组。
所以你需要按数组中的学生的课程价值进行分组。您将应用功能,因此是:
o -> ((Student)o[0]).getCourse()
从而通过实施分组成为:
Map<String, List<Object[]>> resultMap =
resultList.stream().collect(groupingBy(o -> ((Student)o[0]).getCourse()));
顺便说一句,你可能需要使用一类具有类型的数据,避免投,那可能会在运行时抛出异常。您可以在数据库级执行分组。