Search code examples
javasortinggenericswildcardcomparable

Local variable for comparable generic


I'm trying to implement sorting for a generic list of Comparable objects. The problem is that I can't define a local variable for such lists and it leads to code duplicates.

Basically I need a variable that will maintain a returned value from a method with signature
<T extends Comparable<T>> List<Item<T>> getItems(int itemType, Class<T> cl).

Here is the code https://ideone.com/mw3K26. The goal is to avoid code duplicates on lines 25, 26 and 29, 30.

Is it even possible?


Solution

  • Put assosiations itemType -> Class to Map and use it instead if-else.

    private static final Map<Integer, Class<? extends Comparable>> types = new HashMap<>();
    static {
        types.put(1, Long.class);
        types.put(2, Date.class);
    }
    
    public List<Long> getSortedIds(int itemType) {
        Class<? extends Comparable> clz = types.get(itemType);
        if (clz != null) {
            List<Item> items = (List<Item>)getItems(itemType, clz);
            Collections.sort(items);
            return items.stream().map(it -> it.id).collect(Collectors.toList());
        }
        //...
        return null;
    }