繁体   English   中英

在Java对象列表中对项目进行分组

[英]Group items in a list of objects in Java

我正在使用Angular + Java(Oracle -RDBMS)进行Web应用程序。 在页面中,我显示Dto中包含的数据,我在响应中发送回浏览器(显然,它转换为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 ,并使用food name作为键以所需方式显示它。

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

您可以使用地图按食物分组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);
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM