使用不同的方法从列表中删除重复项 [英] Removing duplicates from the list with different ways

查看:120
本文介绍了使用不同的方法从列表中删除重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为employee的类是pojo,我已经创建了这个pojo类型的员工类型的方法的列表。现在我想从列表中删除重复的,请告诉我们实现的各种方法是什么

I have an class called employee that is the pojo , and I have created the list of this pojo type means of employee type..Now I want to remove the duplicates from the list , Please advise what are the various ways to achieve that..

class Emp implements Comparable
{
      String name,job;
      int salary;
      public Emp(String n,String j,int sal)
      {
         name=n;
         job=j;
         salary=sal;
       }
      public void display()
      {
        System.out.println(name+"\t"+job+"\t"+salary);
       }
      public boolean equals(Object o)
      {
          Emp p=(Emp)o;
          return this.name.equals(p.name)&&this.job.equals(p.job)           &&this.salary==p.salary;
       }
       public int hashCode()
       {
          return name.hashCode()+job.hashCode()+salary;
       }  
       public int compareTo(Object o)
       {
          Emp e=(Emp)o;
          return this.name.compareTo(e.name);
           //return this.job.compareTo(e.job);
          // return this.salary-e.salary;

        }
} 

类型..

import java.util.*;
class EmpListDemo
{
      public static void main(String arg[])
      {
          ArrayList list=new ArrayList();
          list.add(new Emp("Ram","Trainer",34000));
          list.add(new Emp("Sachin","Programmer",24000));
          list.add(new Emp("Priyanka","Manager",54000));
          list.add(1,new Emp("Ravi","Administrator",44000));
                 list.add(new Emp("Ram","Trainer",34000));
          list.add(new Emp("Anupam","Programmer",34000));
list.add(new Emp("Sachin","Programmer",24000));
          list.add(new Emp("Sachin","Team Leader",54000));
          System.out.println("There are "+list.size()+" elements in the list.");
          System.out.println("Content of list are : ");
          ListIterator itr=list.listIterator();
          while(itr.hasNext())
          {
            Emp e=(Emp)itr.next();  
            e.display();
          }   

}
}


推荐答案

要从数组列表中删除重复的元素,您应该考虑使用一个哈希集b / c,它们不允许重复。

To remove duplicate elements from an array list you should consider using a hash set b/c they do not allow duplicates.

// Declare your reference variables
ArrayList list = new ArrayList();
HashSet hashSet = new HashSet();

// Put all list elements into hashset
hashSet.addAll(list);
list.clear();
list.addAll(hashSet);

这篇关于使用不同的方法从列表中删除重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆