2

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.

Sri Harsha Chilakapati
  • 11,744
  • 6
  • 50
  • 91

4 Answers4

5

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()]);
Leon
  • 12,013
  • 5
  • 36
  • 59
5

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.

Rich
  • 997
  • 9
  • 12
1

Using Java 8 you can do the following:

String dates[] = {"01-01-1993", "19-11-1993", "01-01-1993", "03-03-2000", "03-03-2000"};
dates = Arrays.stream(dates).distinct().toArray(String[]::new);
Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334
1

this will work simply

 Set<T> tempSet= new HashSet<T>(Arrays.asList(dates));
    String[] dates= tempSet.toArray(new String[tempSet.size()]);//copy distinct values
Rajan Kali
  • 12,627
  • 3
  • 25
  • 37