首页 > 解决方案 > 流获取总记录数并分配回对象

问题描述

我有两条记录,但如何才能将总记录数返回到对象中:

输入

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。

标签: java

解决方案


你可以这样做:

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 + ")";
    }
}

推荐阅读