java - 流获取总记录数并分配回对象
问题描述
我有两条记录,但如何才能将总记录数返回到对象中:
输入
1,开尔文
1,开尔文
2,阿德文
输出
1,开尔文,2
2,艾德文,1
final int total = 0;
Map<String, PersonModel> map = persons.stream()
.collect(Collectors.toMap(f -> f.getCode() + f.getName()
(s, a) -> new PersonModel(
s.Code(),
total + 1
)));
我得到的总数仍然是1。
解决方案
你可以这样做:
List<Input> inputs = Arrays.asList(
new Input(1, "Kelvin"),
new Input(1, "Kelvin"),
new Input(2, "Advin"));
List<Output> results = inputs.stream().collect(Collectors.collectingAndThen(
Collectors.groupingBy(Function.identity(), Collectors.counting()),
map -> map.entrySet().stream()
.map(e -> new Output(e.getKey().getNum(),
e.getKey().getName(),
e.getValue()))
.collect(Collectors.toList())
));
System.out.println(results); // [(1, Kelvin, 2), (2, Advin, 1)]
class Input {
private final int num;
private final String name;
public Input(int num, String name) {
this.num = num;
this.name = name;
}
public int getNum() {
return this.num;
}
public String getName() {
return this.name;
}
@Override
public int hashCode() {
return this.num;
}
@Override
public boolean equals(Object obj) {
return (obj instanceof Input && this.num == ((Input) obj).num);
}
@Override
public String toString() {
return "(" + this.num + ", " + this.name + ")";
}
}
class Output {
private final int num;
private final String name;
private final long count;
public Output(int num, String name, long count) {
this.num = num;
this.name = name;
this.count = count;
}
@Override
public String toString() {
return "(" + this.num + ", " + this.name + ", " + this.count + ")";
}
}
推荐阅读
- java - 无法在类预期参数上找到适当的构造函数是:java.util.collection
- dita-ot - 如果输入参数具有 UNC 路径,则无法在 DITA-OT 中生成字输出
- angular - 如何在 ShadowDom 中使用 mat-icon
- c# - 如何在 ASP.Net Core 的服务层基类中获取当前用户?
- javascript - 在给定的文本偏移处插入 HTML
- python - Openpyxl 工作表不存在
- sql - 在 Oracle 中的两个 Unix 日期之间
- c# - 检查“...\HiQPdf.dep”资源文件可以在 HiQPdf.dll 程序集附近找到,并且用户具有该文件的读取和执行权限
- mongodb - 在 mongoDB 中提交数据
- php - php 7.4 上的 openssl_cipher_iv_length 错误