编号   数量1234     1
1991     1
1234     1
1991     1
1234     1
1991     1
1234     3
1991     3现在在往txt文档写入数据,现在上面的那个集合对象的值是有重复的,现在怎么才能实现下面的结果,把1234的数量设为3,1991的数量设为3?

解决方案 »

  1.   

    用map,key生日,value++
      

  2.   

    可以先将list转化成set,得到无重复元素的集合。再用迭代器,取出set里元素,每取出一个元素将list遍历一遍,并得到每个元素的数量。
      

  3.   

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