0

Lets say I have an array of an array of strings:

ArrayList<ArrayList<String>> arrayOfArray= new ArrayList<ArrayList<String>>();

Maybe it could look something like this(eg.): arrayOfArray = [[A,1,B,2],[C,1,D,2],[C,1,D,2],[A,1,B,2]]

In the end I want this(duplicates was removed): arrayOfArrayNoDuplicates = [[C,1,D,2],[A,1,B,2]]

Then as a final step I want this array of array to be sorted on the first item in the array. Looks like this array of array maybe was sorted on the A or the B. arrayOfArraySorted = [[A,1,B,2],[C,1,D,2]]

Is this possible without also sorting the inner array? I want to keep the order within the array "A,1,B,2".

I hope you understand want I want to do:)

/M

3
  • Instead of list you should use set.It does not allow duplicates and particulary use LinkedHashSet.It maintains insertion order Commented Jun 3, 2014 at 19:42
  • But is this really working for Array of array? Commented Jun 4, 2014 at 3:26
  • Yes it might work..i have not tried it before.. Commented Jun 4, 2014 at 3:47

3 Answers 3

1

You use a set

It functions like an array, it dedupes

Sign up to request clarification or add additional context in comments.

Comments

0

You can use a Set with a Comparator fot that.

Set<List<String>> list = new TreeSet<ArrayList<String>>(
             new Comparator<List<String>>() {
               public int compare(List<String> left, List<String> right) {
                  //check here if equal, before or after...    

               }
             }
         );

Comments

0

You should really use a HashSet or similar to remove duplicates from your collection of data (sets can only contain unique elements). I'm unsure how effective this will be against ArrayList's of varying contents though, so you might be best off extending ArrayList<String> and implementing your own bool equals(Object a) method (for your inner arrays).

To then sort your collection you should using Collections.sort(), you can then pass this a custom Comparator to sort them by whichever order you please. (A comparator lets you provide a method that takes 2 objects and rates their order.) Or if you've extended ArrayList<String> simply add the compare method to your class and add implements Comparator.

An example Comparator would be;

import java.util.*;
class ALComparator implements Comparator<ArrayList<String>>
{
    @Override
    public int compare(ArrayList<String> a, ArrayList<String> b)
    {
        if(a.size()==b.size())
            return 1;
        if(a.size()==0)
            return -1;
        if(b.size()==0)
            return 1;
        return a.get(0).compareTo(b.get(0));
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.