如何在Java Stream中将POJO的列表转换为Map<String,List>?



我想使用 Java 8 Stream API 以非静态方法将 Java POJO 列表转换为 Map。

我的折线图需要轴 x 的日期字符串值列表和轴 y 的数值列表。这是一种典型的地图格式。但是我的数据库为我返回了一个 POJO 列表。我不喜欢在没有Java 8 Stream API帮助的情况下循环。 我已经尝试了这个[ask}(Java 8 List of Objects to Map<String,List> of values(中的方法。但是,我面临两个问题。首先,我的POJO MoreCustomDTO除了字符串之外还包含整数。其次,当我尝试使用方法引用时,IDEA抱怨非静态方法无法从静态上下文中引用。

波乔:

@Data
MoreCustomDTO {
private String date;
private Integer money;
}

DAO 查询方法:

public List<MoreCustomDTO > getMoreCustomCount(@Param("format") String format, @Param("startTime") String startTime, @Param("endTime") String endTime);

Java 8 之前的解决方案:

List<MoreCustomCountDTO> customList = customDao.getMoreCustomCount(SqlUtils.DATE_TYPE_FORMAT[Integer.valueOf(type)],startTime,endTime);
Map<String, List> map = new HashMap();
List<String> dateList = new ArrayList<>();
List<Integer> moneyList = new ArrayList<>();
for (MoreCustomCountDTO data : customList) {
dates.add(data.getDate());
dailyAmounts.add(data.getMoney());
}
map.put("date", dateList);
map.put("money", moneyList);

故障代码段:

Map<String,List> map =
customList.stream()
.flatMap(element -> {
Map<String,String> um = new HashMap<>();
um.put("date",element.getDate());
um.put("money",element.getMoney());
return um.entrySet().stream();
})
.collect(Collectors.groupingBy(Map.Entry::getKey,
Collectors.mapping(Map.Entry::getValue,
Collectors.toList())));

我从数据库中获取一个列表。它是JSON foramt中的一个对象数组。

响应:

{
"rows": [
{
"date": "2019-09-01",
"money": 0.00
},
{
"date": "2019-09-02",
"money": 0.00
}
]
}

但我想要一个(键(对多(值(映射格式。

响应:

{
"map": {
"date": [
"2019-09-01",
"2019-09-02"
],
"money": [
0.00,
0.00
]
}
}

老实说,我认为您最初的解决方案还可以。有时,强制使用语言中最花哨的功能实现解决方案最终会导致代码不那么清晰,这总是一件坏事。

话虽如此,我认为你打算做的是这样的:

Map<Object, Object> map = Stream.of(
new SimpleEntry<>(
"date",
customList.stream().map(MoreCustomDTO::getDate).collect(Collectors.toList())
),
new SimpleEntry<>(
"money",
customList.stream().map(MoreCustomDTO::getMoney).collect(Collectors.toList())
)
).collect(Collectors.toMap(SimpleEntry::getKey, SimpleEntry::getValue));

像这样使用 SimpleEntry:

Map<String, List<Object>> map= customList.stream().
flatMap(element -> 
Stream.of(new AbstractMap.SimpleEntry<String, Object>("date", element.getDate()),
new AbstractMap.SimpleEntry<String, Object>("money", element.getMoney()))).
collect(Collectors.groupingBy(AbstractMap.SimpleEntry::getKey, Collectors.mapping(AbstractMap.SimpleEntry::getValue, Collectors.toList())));

相关内容

最新更新