根据源列表内容将列表转换为列表<列表>

时间:2018-02-20 10:00:14

标签: java collections java-8 java-stream

我有以下对象DataPoint

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

我有名单:

{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.有更简洁的方法来实现它吗?

1 个答案:

答案 0 :(得分:4)

describe('abcd', function() {
     var data = null; //declare data in a scope usable by `before` and `withData` functions

     before(function() {

         // get data synchronously
         data = 'some data';

         // or...

         //return a promise so the tests don't start before the promise resolves
         return getData().then(function (someData) {
           data = someData;
         })
     });

     // nested tests that will start only after `before` function finished executing
     describe('with data', function () {
         withData(data, function(value) {
             it('abccd', function() {
                //test
             });
         });
     });
});

您可以使用 dataPoints.stream() .collect( Collectors.collectingAndThen( Collectors.groupingBy( DataPoint::getUploadIndex, TreeMap::new, Collectors.toList() ) ), map -> new ArrayList(map.values()) ); ;除此之外,你的解决方案对我来说很好。