Java 中的对象列表中的分组项目

Group items in a list of objects in Java

我正在使用 Angular + Java (Oracle -RDBMS) 开发一个网络应用程序。在一个页面中,我显示 Dto 中包含的数据,我在 Responsive 中发送回浏览器(显然是在转换为 json 之后)。它有效,但是这个 Dto 包含一个对象列表,其中包含:

| FOOD | CUSTOMER | COUNT
  Apple     X         3
  Apple     y         1
  Apple     z         5
  Milk      j         2
  Milk      p         1

这是我做的过程:

    List<FoodsDto> foods = new ArrayList<FoodsDto>();
    // I call the query to retrieve the list and I add it ordering for 'foods'...
    // Then I set it on the result 
    result.setFoods(developmentResult);
    // And i send the response on browser...

在 'setFoods' 之前,我想对食物列表进行分组。结果应该是一个包含以下内容的新数组:

| FOOD | CUSTOMER | COUNT
  Apple     X         3
  Apple     y         1
  Apple     z         5
  Milk      j         2
  Milk      p         1

  Apple  9
  Milk   3

'9'和'3'是计数之和,所以是总数。反过来,这些行必须包含一个包含所有信息的子数组。所以:

[Apple 9] --
           |--> Apple x 3
           |--> Apple y 1
           |--> Apple z 5

[Milk  3] --
           |--> Milk j 2
           |--> Milk p 1

我怎样才能'打破'列表并将其分组?

如果您不想创建单独的 DTO,您可以简单地遍历 FoodsDto 列表并使用另一个 Map<String, Integer> 进行分组,如下所示。

Map<String, Integer> foodGroup = new HashMap<>();
 for(FoodsDto foodsDto : foods) {
    if(foodGroup.containsKey(foodsDto.getFood())){
       foodGroup.put(foodsDto.getFood(), (foodGroup.get(foodsDto.getFood()) + foodsDto.getCount())); 
    } else {
       foodGroup.put(foodsDto.getFood(), foodsDto.getCount());
    }
}

然后在回复中也发送 foodGroup。在前端(在Javascript/AngularJs),你需要映射foodGroupfoods,使用食物名称作为键来显示它。

'9' and '3' is the som of the count, so the total. In turn these lines must contain a subarray with all information.

您可以使用地图按食物对 FoodsDto 项进行分组:

    Map<FoodsDto, List<FoodsDto>> map = new HashMap<>();        

    for(FoodsDto o : developmentResult){
        // using the FoodsDto as the key
        if (map.get(o) != null) {
            map.get(o).add(o);
        } else {
            List<FoodsDto> foodList = new ArrayList<FoodsDto>();
            foodList.add(o);
            map.put(o, foodList);
        }
    }

    for (Map.Entry<FoodsDto, List<FoodsDto>> entry : map.entrySet()) {
        List<FoodsDto> list = entry.getValue();
        System.out.println(String.format("%s: %d", entry.getKey(), list.size()));

        for(FoodsDto f : list){
            System.out.println(f);
        }
    }