我们可以转换List <map <string,object =“”>&gt; to map <object,map <string,=“”object =“”>&gt;使用Streamby的groupby

时间:2016-02-02 16:30:30

标签: java-8 java-stream collectors

我有List<Map<String, Object>>这样的列表

[{"A": 2616100,
      "B": 2616100,
      "C": 31,
      "D": "Sold Promissory Buyer"
    },
    {
      "A": 101322143.24,
      "B": 50243301.2,
      "C": 569,
      "D": "Auction"
    },
    {
      "A": 72000,
      "B": 93900,
      "C": 1,
      "D": "Sold Third Party"
    }]

将Stream API与groupBy方法salesReportForSoldProperty.stream().collect(Collectors.groupingBy(tags -> tags.get("D")))一起使用,我可以获得集合Map<Object, List<Map<String, Object>>>  
但是当我试图创建这个集合的JSON时,我就像这样得到Json

  {
  "Sold Promissory Buyer": [
    {
      "A": 2616100,
      "B": 2616100,
      "C": 31,
      "D": "Sold Promissory Buyer"
    }
  ],
  "Auction": [
    {
      "A": 101322143.24,
      "B": 50243301.2,
      "C": 569,
      "D": "Auction"
    }
  ],
  "Sold Third Party": [
    {
      "A": 72000,
      "B": 93900,
      "C": 1,
      "D": "Sold Third Party"
    }
  ]
}

这里的每个值都是JSONArray,因为我得到了Map<Object, List<Map<String, Object>>>。有没有办法使用Stream API获取Map<Object, Map<String, Object>>集合,所以我可以得到一个合适的JSON(没有JSONArray值)

1 个答案:

答案 0 :(得分:2)

您应该使用Collectors.toMap代替:

salesReportForSoldProperty.stream().collect(
    Collectors.toMap(tags -> tags.get("D"), Function.identity()));

请注意,在这种情况下,如果您的输入包含两个具有相同"D"值的元素,则您将获得IllegalStateException,因为您无法将两个值放入同一个地图键中。如果要忽略重复项,可以将merge函数指定为第三个参数:

salesReportForSoldProperty.stream().collect(
    Collectors.toMap(tags -> tags.get("D"), Function.identity(), (a, b) -> a));