0

I have this ArrayList, that contains other ArrayLists

Original: [[EHM, Evans, 45], [AB, Evans, 63], [J, Jones, 72], [RA, Jones, 85], [B, Smith, 55]]

I'd like to sort this ArrayList in alphabetical order, to give this output

Desired: [[AB, Evans, 63], [B, Smith, 55], [EHM, Evans, 45], [J, Jones, 72], [RA, Jones, 85]]

This data is based on a textfile that i'm importing, so may change. I want to compare position 0 in each ArrayList and sort alphabetically. Currently the original list sits within a variable 'multiMarkArray'

How would I go about doing this in Java?

Thanks for any input - Phil

4

2 Answers 2

1

Good and clean way to do is this:

// [[EHM, Evans, 45], [AB, Evans, 63]
List<List<String>> input = new ArrayList<>();
List<String> subInput;
subInput = new ArrayList<>();
subInput.add("EHM");
subInput.add("Evans");
subInput.add("45");
input.add(subInput);
subInput = new ArrayList<>();
subInput.add("AB");
subInput.add("Evans");
subInput.add("63");
input.add(subInput);

Collections.sort( input, (a,b) -> a.get(0).compareTo(b.get(0)) );
System.out.println(input);
Sign up to request clarification or add additional context in comments.

1 Comment

@venomphil please accept my answer if you think it helped answer your question
0

You can use TreeSet of TreeSets.

TreeSet<TreeSet<String>> set = new TreeSet<>((s1, s2) -> s1.first().compareTo(s2.first()));
Set<String> subset1 = new TreeSet<>();
subset1.add("EHM");
subset1.add("Evans");
subset1.add("45");
Set<String> subset2 = new TreeSet<>();
subset2.add("AB");
subset2.add("Evans");
subset2.add("43");
set.add(subset1);
set.add(subset2);

TreeSets are sorted.

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.