Java 2D ArrayList and sorting

前端 未结 3 1450
执笔经年
执笔经年 2021-01-22 22:52

I need to sort a shopping list by the aisle the item is located for example:
[Bread] [1]
[Milk] [2]
[Cereal] [3]

I am planning to do this with ArrayList and

3条回答
  •  有刺的猬
    2021-01-22 23:24

    I know the question was asked long ago but actually i had the same problem. If you dont know how many variables you would have on list but this is not a big number you could just implement comparator for every choose. eg

    I have ArrayList> and want to sort it by column's and i know that the nested list consist of variable number of objects i can just implement comparator for every possible value:

    public class SecondColumnComparator implements Comparator {
    
    public static boolean isNumeric(String str) {
        try {
            Integer integer = Integer.parseInt(str);
        } catch (NumberFormatException nfe) {
            return false;
        }
        return true;
    }
    
    @Override
    public int compare(Object o1, Object o2) {
    
        if (isNumeric(((ArrayList) o1).get(1))) {
    
            Integer firstInteger = Integer.parseInt(((ArrayList) o1).get(1));
            Integer secondInteger = Integer.parseInt(((ArrayList) o2).get(1));
    
            return firstInteger.compareTo(secondInteger);
    
        }
        if (((ArrayList) o1).get(1) instanceof String) {
    
            String firstString = ((ArrayList) o1).get(1);
            String secondString = ((ArrayList) o2).get(1);
    
            return firstString.compareTo(secondString);
        }
    
        throw new Exception();
    }
    
    
    

    }

    And call this this way:

            switch (valueSelected) {
            case 0:
                Collections.sort(this.listOfLists, new FirstColumnComparator());
                break;
            case 1:
                Collections.sort(this.listOfLists, new SecondColumnComparator());
                break;
            case 2:
                Collections.sort(this.listOfLists, new ThirdColumnComparator());
                break;
            case 3:
                Collections.sort(this.listOfLists, new FourthColumnComparator());
                break;
            default:
    
        }
    

    In every comparator just modifying .get(x) where x is number of collumn by which you want sort.

    The boolean isNumeric(String str); function may be used because you cant store different type of objects on one list so I put the recognition of this to the comparator and parse String to any other type.

    Remember that this comparator and its "calculations" are called to every single comparison made by algorithm so it is extremely inefficient... Despite this fact this is kind of sollution.

    提交回复
    热议问题