Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove duplicates in following java code?

Tags:

java

I have written the following code and i am getting all the duplicates even i have used set.

private void validatingpswwithpattern(String password) throws IOException

  {
            List<String[]> list=new ArrayList<String[]>();
            list.add(new String[]{"raj","duvva","sathish"});
            list.add(new String[]{"raj","duvva","sathish"});
            list.add(new String[]{"raj","duvva","sathish"});
            list.add(new String[]{"raj","duvva","sathish"});
            list.add(new String[]{"raj","duvva","sathish"});
            list.add(new String[]{"raj","duvva","sathish"});


            Set<String[]> hs = new HashSet<String[]>();
             hs.addAll(list);
             list.clear();
             list.addAll(hs);
             System.out.println(list);
}
like image 482
Srinath Murugula Avatar asked Mar 14 '26 07:03

Srinath Murugula


1 Answers

Since arrays don't override the default implementation of hashCode and equals from Object class, HashSet is useless for eliminating duplicates.

You could use a TreeSet and supply a Comparator<String[]> that would determine when two String arrays are equal.

TreeSet<String[]> set = new TreeSet<> (new Comparator<String[]>() {
  public int compare(String[] o1, String[] o2)
  {
    // write here logic to determine whether o1<o2 (return -1) or
    //                                       o1>o2 (return 1) or 
    //                                       o1 is equal to o2 (return 0)
  }
});
set.addAll(list);
like image 198
Eran Avatar answered Mar 16 '26 21:03

Eran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!