Select the line which should be inserted in the comparator body below, so that the treeMap keys will be sorted in ascending order (COM1 COM2 COM8 etc).

public class Main {
    public static void main(String[] args) {
        Comparator<String> comparator = new Comparator<String>() {
                public int compare(String string_1, String string_2) {
                    //insert code here
        TreeMap<String, String> treeMap = new TreeMap<String, String>(comparator);
        treeMap.put("COM1", "\\Device\\Serial0");
        treeMap.put("COM2", "\\Device\\Serial1");
        treeMap.put("COM8", "\\Device\\Nmserial0");
        treeMap.put("COM9", "\\Device\\Nmserial1");
        treeMap.put("COM10", "\\Device\\Nmserial2");
        treeMap.put("COM11", "\\Device\\Nmserial3");
The TreeSet expects the comparator to return a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second. Accordingly, to compare the keys, we need to extract the number from the string using replace("COM", "") method, and then apply the Integer.valueOf() method. Subtracting one Integer from another and returning the result will make our comparator behave as the TreeMap expects.

Слідкуй за CodeGalaxy

Мобільний додаток Beta

Get it on Google Play
Зворотній Зв’язок
Продовжуйте вивчати
тести з Java
Зареєструйся Зараз
або Підпишись на майбутні тести