Sort with a Lambda

Lab Java Intermediate 20 points

Read n words and sort them by length, then alphabetically, using list.sort(...) with a lambda. Print them on one line.

Input

n, then n words.

Output

One line.

Example

Input

5
banana kiwi apple fig cherry

Output

fig kiwi apple banana cherry
Sample input available Sample output available
Editor
Java

Hints

(a, b) -> ... is a lambda implementing Comparator.

String.join(" ", list) joins with spaces.

Solution explanation

A lambda is a short way to write an object with a single method - here a Comparator. The diamond <> lets the compiler infer the type.

Show solution
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        List<String> words = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            words.add(sc.next());
        }
        words.sort((a, b) -> a.length() != b.length() ? a.length() - b.length() : a.compareTo(b));
        System.out.println(String.join(" ", words));
    }
}
Output
Answer
HOME LEARN COMMUNITY DASHBOARD