天天看点

Java中TreeSet合并重复数据

TreeSet与HashSet之间的区别:

TreeSet会自动按自然排序法给元素排序,相应的性能会差一点。而HashSet是根据元素的hashCode自动给元素排序的,如果我们不需要使用排序功能,则应该使用HashSet。

相应的使用TreeSet的对象需要实现Comparable接口,并重写compareTo方法。

package com.test;

public class T implements Comparable<T>{
	private int t_id;
	private String t_name;
	T(int id,String name) {
		this.setT_id(id);
		this.setT_name(name);
	}
	public int getT_id() {
		return t_id;
	}
	public void setT_id(int t_id) {
		this.t_id = t_id;
	}
	public String getT_name() {
		return t_name;
	}
	public void setT_name(String t_name) {
		this.t_name = t_name;
	}
	public int compareTo(T o) {
		if (this.getT_id()<o.getT_id()) {
			return -1;
		}if (this.getT_id()>o.getT_id()) {
			return 1;
		}else {
        //如果t_id相等的话就无法添加
			return 0;
		}
	}

}
           

[size=large][color=red][b]合并重复数据:

[/b][/color][/size]当出现重复数据时不添加,但是在更改重复数据的内容-类似于网购:如果你添加相同的订单,它只会在数量上加1而不是添加多一条记录(个人理解,至于真正的网购是怎么处理的我也不清楚)。

import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;

public class T implements Comparable<T>{
	private int t_id;
	private int t_num;
	private String t_name;
	T(){
	}
	T(int id,int num,String name) {
		this.setT_id(id);
		this.setT_num(num);
		this.setT_name(name);
	}
	public int getT_id() {
		return t_id;
	}
	public void setT_id(int t_id) {
		this.t_id = t_id;
	}
	public int getT_num() {
		return t_num;
	}
	public void setT_num(int t_num) {
		this.t_num = t_num;
	}
	public String getT_name() {
		return t_name;
	}
	public void setT_name(String t_name) {
		this.t_name = t_name;
	}
	public int compareTo(T o) {
		if (this.getT_name().equals(o.getT_name())) {
//重复不添加,只修改其中的num值--o为set中存在的对象
			o.setT_num((this.getT_num())+o.getT_num());
			return 0;
		}else {
//固有排序
			if (this.getT_id()<o.getT_id()) {
				return -1;
			}
			if (this.getT_id()>o.getT_id()) {
				return 1;
			}
			else {
				//如果t_id相等的话就无法添加
				return 0;
			}
		}
	}
	public static void main(String[] args) {
		T t0=new T(0,1,"t0000");
		T t1=new T(1,1,"t1111");
		T t2=new T(2,1,"t2222");
		T t2_add=new T(2,9,"t2222");
		Set<T> set=new TreeSet();
		set.add(t0);
		set.add(t1);
		set.add(t2);
		set.add(t2_add);
		System.out.println(set.size());
		for (Iterator iterator = set.iterator(); iterator.hasNext();) {
			T t = (T) iterator.next();
			System.out.println("value="+"---"+t.getT_id()+"---"+"数量:"+t.getT_num()+"---"+t.getT_name());
		}
	}
}
输出结果:
3
value=---0---数量:1---t0000
value=---1---数量:1---t1111
value=---2---数量:10---t2222    //原来数量为1的,后来加了一条数量为9的数据