<分区>
我尝试使用 java 8 功能。
我有课
@Data
@NoArgsConstructor
@AllArgsConstructor
class User {
private String pId;
private String uId;
private String price;
}
我有一个列表,我尝试按 pId
分组并计算非 null uId
和 price
。示例:
List<User> list =
Arrays.asList(
new User ("p1", "u1", null),
new User ("p1", "u2", "a"),
new User ("p2", null, "b"),
new User ("p2", null, "c"),
new User ("p3", "u4", "d")
);
我的预期输出是
[
{ pId:"p1", uCount:2, priceCount:1 },
{ pId:"p2", uCount:0, priceCount:2 },
{ pId:"p3", uCount:1, priceCount:1 }
]
我试过喜欢下面
Map<String, Map<Object, Long>> collect =
list.stream()
.collect(
Collectors.groupingBy(
User ::getPId,
Collectors.groupingBy(f -> f.getUId(), Collectors.counting())));
我的最终映射类是
@Data
@NoArgsConstructor
@AllArgsConstructor
class Stat {
private String pId;
private Integer uCount;
private Integer priceCount;
}
由于我是 java 的新手,我面临着完成它的困难,我尽力了。是否可以删除空字段并计数?