Reputation: 36984
I have following object DataPoint
:
public class DataPoint {
private String name:
private int uploadIndex;
...
}
I have 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"}
I want to transform it to the List<List<DataPoint>>
sorted by uploadIndex
.
Result should be(ordering inside the internal list is not important):
{
{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"}
}
I wrote following code:
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. Does this code guarantee the ordering?
2. Is there more concise way to implement it?
Upvotes: 3
Views: 78
Reputation: 120858
dataPoints.stream()
.collect(
Collectors.collectingAndThen(
Collectors.groupingBy(
DataPoint::getUploadIndex,
TreeMap::new,
Collectors.toList()
)
),
map -> new ArrayList(map.values())
);
You could use Collectors.collectingAndThen
; other than that your solution looks fine to me.
Upvotes: 4