怎么才能去除arraylist重复原生并计数

Chills7191 2016-04-14 12:29:57
编号 数量

1234 1
1991 1
1234 1
1991 1
1234 1
1991 1


1234 3
1991 3

现在在往txt文档写入数据,现在上面的那个集合对象的值是有重复的,现在怎么才能实现下面的结果,把1234的数量设为3,1991的数量设为3?
...全文
92 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
scmod 2016-04-14
  • 打赏
  • 举报
回复
用map,key生日,value++
bree06 2016-04-14
  • 打赏
  • 举报
回复
java8下测试.

import java.util.ArrayList;
import java.util.List;
import java.util.TreeSet;
import java.util.stream.Collectors;

public class Demo32 {

    public static void main(String[] args) {
        // TEST DATA
        List<PNode> list = new ArrayList<PNode>();
        list.add(new PNode("1234", 1));
        list.add(new PNode("1234", 1));
        list.add(new PNode("1234", 1));
        list.add(new PNode("1991", 1));
        list.add(new PNode("1234", 2));
        list.add(new PNode("1991", 10));
        list.add(new PNode("1991", 10));
        list.add(new PNode("1234", 3));
        list.add(new PNode("a", 2));
        list.add(new PNode("b", 12));
        list.add(new PNode("a", 1));

        TreeSet<PNode> tsNode = list.parallelStream().collect(Collectors.toCollection(() -> new TreeSet<PNode>((x, y) -> {
            if (x == y) return 0;
            int _t = x.getNo().compareTo(y.getNo());
            if (_t == 0) {
                int t = x.getTotal() + y.getTotal();
                x.setTotal(t);
                y.setTotal(t);
            }
            return _t;
        })));

        tsNode.forEach(System.out::println);
    }

}

class PNode {
    private String no;
    private int total;

    public PNode() { };

    public PNode(String no, int total) {
        this.no = no;
        this.total = total;
    }

    public String getNo() {
        if (no == null) {
            no = "";
        }
        return no;
    }

    public void setTotal(int total) {
        this.total = total;
    }

    public int getTotal() {
        return total;
    }

    @Override
    public String toString() {
        return String.format("{\"no\": \"%s\", \"total\": %d}", getNo(), total);
    }
}
  • 打赏
  • 举报
回复
1楼+1.。。
小白云天 2016-04-14
  • 打赏
  • 举报
回复
可以先将list转化成set,得到无重复元素的集合。再用迭代器,取出set里元素,每取出一个元素将list遍历一遍,并得到每个元素的数量。

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧