Collections.max with Comparator

Lab Java Intermediate 20 points

Read n words. Print the longest word (first on ties) using Collections.max with a Comparator, and the alphabetically first word with Collections.min.

Input

n, then n words.

Output

Two lines.

Example

Input

5
fig banana kiwi cherry apple

Output

banana
apple
Sample input available Sample output available
Editor
Java

Hints

A Comparator decides which of two items is 'bigger'.

Solution explanation

Breaking ties by original position makes the earlier word count as 'larger', so it wins.

Show solution
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
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();
        final List<String> words = new ArrayList<String>();
        for (int i = 0; i < n; i++) {
            words.add(sc.next());
        }
        String longest = Collections.max(words, new Comparator<String>() {
            public int compare(String a, String b) {
                if (a.length() != b.length()) {
                    return Integer.compare(a.length(), b.length());
                }
                return Integer.compare(words.indexOf(b), words.indexOf(a));
            }
        });
        System.out.println(longest);
        System.out.println(Collections.min(words));
    }
}
Output
Answer
HOME LEARN COMMUNITY DASHBOARD