1

I have a collection with data like:

John eats candy
Richard runs around in the morning
Hannah drinks water

I divided each word, added it to the array and got:

[John, eats, candy]
[Richard, runs, around, in, the, morning]
[Hannah, drinks, water]

The output should be (the second words are sorted alphabetically)

[Hannah, drinks, water]
[John, eats, candy]
[Richard, runs, around, in, the, morning]

Here is my code:

        List<List<String>> mainList = new ArrayList<>();
        List<String> list = new ArrayList<>();
        for (String s : array) {
            String[] x = s.split(" ");
            for (int i = 0; i < x.length; i++) {
                list.add(x[i]);
            }
            mainList.add(list);
            list = new ArrayList<>();
        }

But I do not know what to do next. How to implement a comparison of the elements and, based on this, replace the lines. Is it right at all to divide strings into arrays to get access to the second element? I will be happy, even if you just advise something.

xingbin
  • 27,410
  • 9
  • 53
  • 103
J.doe
  • 13
  • 4
  • 1
    **Hint 1**: first try to write a method that takes two of these lists and returns an `int` value: +1 if the second list is "greater than" the first, -1 if it's "less than" the first, and 0 if they're "equal". **Hint 2:** pay attention to the fact that some lines may only contain a single word. **Hint 3:** look up `Collections.sort()` in the Java API docs. (Or `List.sort()` if you're using Java 8.) – biziclop Aug 31 '18 at 11:54
  • 1
    @biziclop I would have felt really bad closing this as duplicate, but after your comments, you made my life easier. thank you – Eugene Aug 31 '18 at 12:01

1 Answers1

5

At first attempt, you can wirte a Comparator:

class ListComparator implements Comparator<List<String>> {
    @Override
    public int compare(List<String> o1, List<String> o2) {
        return o1.get(1).compareTo(o2.get(1));
    }
}

mainList.sort(new ListComparator());

In java-8, it can be shorten to this:

mainList.sort(Comparator.comparing(strings -> strings.get(1))); // compare using the second element(index 1) of every list
xingbin
  • 27,410
  • 9
  • 53
  • 103