Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete similar elements from String array or ArrayList [duplicate]

I'm totally new to programming and I have String array:

String dates[] = {"01-01-1993", "19-11-1993", "01-01-1993", "03-03-2000", "03-03-2000"};

In the above array dates[0] == dates[2] and dates[3] == dates[4], I want to delete the duplicate values which IS REPEATED and I want program to produce result like this:

dates[] = {"01-01-1993", "19-11-1993", "03-03-2000"}

Some are using ArrayList concept some are using complex for loops and I'm confused, so could you please help in achieving the above task.

Thanks In Advance.

like image 720
JayaSantoshKumar Avatar asked Mar 27 '26 19:03

JayaSantoshKumar


2 Answers

You can use a Set to remove duplicates.

Set<T> dateSet = new HashSet<T>(Arrays.asList(dates));

dateSet will only contain unique values.

If you need to get back to an array

dates = dateSet.toArray(new String[dateSet.size()]);
like image 118
Leon Avatar answered Mar 29 '26 08:03

Leon


Your question raises a few points:

  1. In general, this kind of manipulation of collections is much easier and cleaner if you use the Collection classes (Set, List, etc). For example, a Set guarantees uniqueness of the elements:

    String dates[] = {"01-01-1993", "19-11-1993","01-01-1993","03-03-2000","03-03-2000"};
    Set<String> uniqueDates = new HashSet<>(Arrays.asList(dates));
    

But HashSet is unordered; if you iterate over uniqueDates the order in which you get the back is arbitrary. If the order is important, you could use LinkedHashSet:

Set<String> orderedUniqueDates = new LinkedHashSet<>(Arrays.asList(dates));
  1. The basic collection that come with Java are pretty good; but if you use Google's Guava library (https://github.com/google/guava), it gets really nice and you can do really powerful things like finding intersections of sets, set differences etc.:

    Set<String> uniqueDates = Sets.newHashSet(dates);
    
  2. More fundamentally, String is a very poor choice of data type to represent Dates. Consider using either java.util.Date or (if using a Java version prior to 8) org.joda.time.DateTime (http://www.joda.org/joda-time/). Not only will this give you type safety and ensure that your data is really all dates, but you could then do things like sorting.

like image 34
Rich Avatar answered Mar 29 '26 08:03

Rich



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!