[英]Restructure List<MyType> to List<List<MyType>>
I have an ArrayList which looks like this:我有一个 ArrayList 看起来像这样:
final List<MyType> myList = new ArrayList<>();
MyType looks like this: MyType 看起来像这样:
public class MyType {
...
private DateTime startTime;
private DateTime endTime;
private DateTime dateOfContainer; // I use @JSONSerializer here to only serialize date
....
}
The JSON looks like this: JSON 如下所示:
[
{
...
"endTime": "16:00",
"startTime": "13:00",
"dateOfContainer": "27.11.2015"
},
{
...
"endTime": "12:00",
"startTime": "08:00",
"dateOfContainer": "27.11.2015"
},
{
...
"endTime": "16:00",
"startTime": "13:00",
"dateOfContainer": "25.11.2015"
},
{
...
"endTime": "19:00",
"startTime": "18:00",
"dateOfContainer": "21.11.2015"
},
...
Now I would a list like this:现在我想要一个这样的列表:
List<List<MyType>>
where MyType's with the same dateOfContainer are together, eg the first two.其中具有相同dateOfContainer 的MyType 在一起,例如前两个。
Is there a simple way with Java-8 to do this? Java-8 有没有一种简单的方法可以做到这一点? Thanks a lot!
非常感谢!
myList.stream().collect (Collectors.groupingBy(MyType::getDateOfContainer))
will give you a Map<DateTime,List<MyType>>
where your objects are grouped by the date property. myList.stream().collect (Collectors.groupingBy(MyType::getDateOfContainer))
会给你一个Map<DateTime,List<MyType>>
,你的对象按日期属性分组。
To get a List<List<MyType>>
from this Map
, you can create an ArrayList
and initialize it with the values of that Map
:要从此
Map
获取List<List<MyType>>
,您可以创建一个ArrayList
并使用该Map
的值对其进行初始化:
List<List<MyType>> list = new ArrayList<> (
myList.stream().collect (Collectors.groupingBy(MyType::getDateOfContainer)).values());
Note that in order for groupingBy
to function as expected, the DateTime
class must override equals
.请注意,为了使
groupingBy
能够按预期运行, DateTime
类必须覆盖equals
。 I'm not sure if that's the case here.我不确定这里是否是这种情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.