-2

I have a linked list of arrays of strings.

List<String[]> list = new LinkedList<>();

Each element of this list contains elements of the form:

["word1", "example1", "2"]

How do I sort the list by the first string element in each array lexicographical?

Zabuzard
  • 25,064
  • 8
  • 58
  • 82
  • Don’t use `LinkedList`. Use `ArrayList`. – Ole V.V. Jul 05 '21 at 05:25
  • 1
    Also take a look here https://stackoverflow.com/questions/8069370/is-an-arraylist-or-a-linkedlist-better-for-sorting – silentsudo Jul 05 '21 at 05:53
  • While LinkedList is very good at adding and removing elements in the middle of array, its random access (as needed in sorting) is not as good. Typically ArrayList is preferred, while this may depend on what else do you need to do with this array. – Audrius Meškauskas Jul 05 '21 at 06:41

2 Answers2

5

You need to provide a Comparator that compares the first values of the arrays.

list.sort(Comparator.comparing(a -> a[0]));

Test

List<String[]> list = new LinkedList<>();
list.add(new String[] { "word1", "example1", "2" });
list.add(new String[] { "ahead", "invention", "3" });
list.add(new String[] { "sip", "nerve", "4" });

list.sort(Comparator.comparing(a -> a[0]));

list.forEach(a -> System.out.println(Arrays.toString(a)));

Output

[ahead, invention, 3]
[sip, nerve, 4]
[word1, example1, 2]
Andreas
  • 154,647
  • 11
  • 152
  • 247
4

Can use the below code for sorting a List. I guess this should suffice your purpose.

Collections.sort(list, new Comparator<String[]>() {
        @Override
        public int compare(String[] arr1, String[] arr2) {
            return arr1[0].compareTo(arr2[0]);
        }
    });

If you're using Java 8 and above, then you can achieve the same with below line of code.

list.sort((arr1, arr2) -> arr1[0].compareTo(arr2[0]));
  • 1
    Works. Note though that since Java 8 there is a much more concise and compact way of doing this, avoiding all the anonymous-class stuff (see the other answer). – Zabuzard Jul 05 '21 at 06:43
  • 1
    If you're not using Java 8, then `List` doesn't have a `sort()` method, so both examples require Java 8. – Andreas Jul 05 '21 at 09:19
  • 1
    I updated my solution to make it more generic and included syntax for Java 8. – Pancham Goyal Jul 05 '21 at 11:36