0

I was wondering if there was a way to find duplicate elements in an arraylist. For more context of what I'm trying to do, I have an arraylist of strings. The strings each contain information about an MP3 file. They have a title, composer, and running time seperated by a '&' character (e.g. Friday&Rebecca Black&666).

The arraylist has already been quicksorted according to the running times. However, I also need to sort the arraylist so that if the running times for songs are equal they should be put into lexicographic order on the title, and then on the composer if the titles are equal as well.

I want to be able to find duplicate running times in the arraylist so that I can use the compareTo method to sort alphabetically like I need to. I have already implemented methods getTime, getTitle, getComposer that extract the relevant information from the overall strings. Is there a way I could do this in a new method such as alphabetical, or even better is there a way I could incorporate it into my quicksort algorithm so I don't have to search through the sorted arraylist again?

Thanks.

Jigglypuff
  • 1,433
  • 6
  • 24
  • 38

2 Answers2

7

You need to change the Comparator for your sort, so that in the event of a tie (equal running time) it looks at the title and composer. See:

 java.util.Collections.sort(List list, Comparator c) 

particularly the principal method:

int compare(Object o1, Object o2) 
DNA
  • 42,007
  • 12
  • 107
  • 146
  • I thought about doing that, but I'm not sure which elements of the arraylist I should be comparing. I'm using a quicksort algorithm similar to the first one mentioned here: [link](http://en.wikipedia.org/wiki/Selection_algorithm#Optimised_sorting_algorithms) but the partition method only compares between i and the pivotValue. – Jigglypuff May 27 '11 at 20:01
  • 1
    You don't need to worry about that - the comparator just needs to be able to compare any two elements correctly, including the tie-breaks; you provide it to Collections.sort() which does all the work for you. – DNA May 27 '11 at 20:02
2

Removing the duplicate elements in your list is not the best way to achieve your goal. Instead, look into using either a Comparator (if there will be multiple sorting methods), or having your MP3File class implement Comparable (if there is only one, or there is clearly a best one).

Ben Hocking
  • 7,790
  • 5
  • 37
  • 52