gpt4 book ai didi

java - 根据源List内容将List转换为List

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:02:00 26 4
gpt4 key购买 nike

我有以下对象 DataPoint :

public class DataPoint {
private String name:
private int uploadIndex;
...
}

我有 list :

{uploadIndex:1, name:"name_1"}
{uploadIndex:5, name:"name_2"}
{uploadIndex:3, name:"name_3"}
{uploadIndex:3, name:"name_4"}
{uploadIndex:4, name:"name_5"}
{uploadIndex:5, name:"name_6"}
{uploadIndex:2, name:"name_7"}
{uploadIndex:4, name:"name_8"}

我想将其转换为 List<List<DataPoint>>uploadIndex 排序.
结果应该是(在内部列表中排序并不重要):

{
{uploadIndex:1, name:"name_1"}
}
{
{uploadIndex:2, name:"name_7"}
}
{
{uploadIndex:3, name:"name_3"}
{uploadIndex:3, name:"name_4"}
}
{
{uploadIndex:4, name:"name_5"}
{uploadIndex:4, name:"name_8"}
}
{
{uploadIndex:5, name:"name_2"}
{uploadIndex:5, name:"name_6"}
}

我写了下面的代码:

List<DataPoint> dataPoints = getFromDb();
Map<Integer, List<DataPoint>> groupedDataPoints = dataPoints.stream()
.collect(Collectors.groupingBy(DataPoint::getUploadIndex, TreeMap::new, Collectors.toList()));
List<List<DataPoint>> groupedList = new ArrayList<>(groupedDataPoints.values());

<强>1。此代码是否保证顺序?
2、有没有更简洁的实现方式?

最佳答案

 dataPoints.stream()
.collect(
Collectors.collectingAndThen(
Collectors.groupingBy(
DataPoint::getUploadIndex,
TreeMap::new,
Collectors.toList()
)
),
map -> new ArrayList(map.values())
);

您可以使用Collectors.collectingAndThen;除此之外,您的解决方案对我来说还不错。

关于java - 根据源List内容将List转换为List<List>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48882465/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com