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

venomphil
  • 39
  • 1
  • 8
  • 1
    Possible duplicate of [java Arrays.sort 2d array](https://stackoverflow.com/questions/15452429/java-arrays-sort-2d-array) – alexandrum Mar 11 '19 at 20:58
  • [This](https://stackoverflow.com/questions/2839137/how-to-use-comparator-in-java-to-sort) might help – lucidbrot Mar 11 '19 at 20:58
  • 2
    Your question **must** include a summary of the work you've done so far to solve the problem, and a description of the difficulty you are having solving it ([help], [ask]). – Zabuzard Mar 11 '19 at 20:59
  • If you can use TreeSet, its members are sorted and you can use your custom comparator to sort. – GaripTipici Mar 11 '19 at 21:26

2 Answers2

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);
Harshit Sharma
  • 313
  • 4
  • 19
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.

GaripTipici
  • 485
  • 1
  • 7
  • 25