• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
山高我为峰
博客园    首页    新随笔    联系   管理    订阅  订阅
Java List合并去重

List A和B

A.removeAll(B);
A.addAll(B);

例如有如下实体类:


/**
 * hashset是如何保持元素的唯一性呢?
 * 是通过元素的hashcode和equals来表示:
 * 如果hashCode值一样,则比较equals是否为true
 * 如果hashCode值不一样,不用比较equals
 */
/**
 * List是如何集合中元素相同的呢?
 * 是通过元素的hashcode和equals来表示:
 * 如果hashCode值一样,则比较equals是否为true
 * 如果hashCode值不一样,不用比较equals
 */
public class UserTable {
    private String linkdoodid;

    private String linkdoodname;

  public UserTable() { super(); }
  public UserTable(String linkdoodid,String linkdoodname){
    supert();
    this.linkdoodid=linkdoodid;
    this.linkdoodname=linkdoodname;
  }
public String getLinkdoodid() { return linkdoodid; } public void setLinkdoodid(String linkdoodid) { this.linkdoodid = linkdoodid == null ? null : linkdoodid.trim(); } public String getLinkdoodname() { return linkdoodname; } public void setLinkdoodname(String linkdoodname) { this.linkdoodname = linkdoodname == null ? null : linkdoodname.trim(); } @Override public boolean equals(Object obj) { if (!(obj instanceof UserTable)) { return false; } UserTable userTable = (UserTable) obj; return this.linkdoodid.equals(userTable.linkdoodid); } @Override public int hashCode() { return linkdoodid.hashCode(); } }

 测试:

public class HashSetTest {
    public static void main(String[] args) {
    //List
    List<UserTable> listA=new ArrayList<UserTable>();
    listA.add(new UserTable("A1001","LJ"));
    listB.add(new UserTable("B1002","MH"));

    List<UserTable> listB=new ArrayList<UserTable>();
    listB.add(new UserTable("B1002","SM"));
    listB.add(new UserTable("C1001","TM"));
    
    listA.removeAll(listB);//由于UserTable的hashCode和equal 都是以linkdoodid 来判断,所以“B1002”算重复元素    
    listA.addAll(listB);

    //HashSet    HashSet
<UserTable> hs = new HashSet<UserTable>();    hs.add(new UserTable("a1", 20));    hs.add(new UserTable("a2", 30));    hs.add(new UserTable("a3", 40));    hs.add(new UserTable("a3", 40));    Iterator<Person> iterator = hs.iterator();    while(iterator.hasNext()){    Person p = iterator.next();    System.out.println(p.getName()+" "+p.getAge());   } } }

 

posted on 2016-12-30 13:43  山高我为峰  阅读(7000)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3