Search code examples
javacollectionsinterfacecomparableiterable

Sorting an list of type `List<Iterable<Object>>`


I have a list of type List<Iterable<Object>> and in some case the objects that are inside the collection are also Comparable.

That means that in some cases it is a list that contains many objects of type A that is not Comparable, in some other cases it contains many objects of type B that are Comparable. When I have a list of objects of type B, I want to be able to sort them.

When all the objects inside the list are Comparable I need to sort them, using Collections.sort() or something similar. Java does not allow me to cast the entire list, and I can't cast single elements, because they may not implement the Comparable interface. Is there a work around?

If it is useful, this is my code:

    Iterable<Object> iterable;

    List<Iterable<Object>> valori = new ArrayList<Iterable<Object>>();

    Integer valoriLetti = 0;

    iterable = new ArrayList<Object>();
    while (iterable != null && valoriLetti < numero) {
        // Object object = beanReader.read();
        try {
            iterable = (Iterable<Object>) beanReader.read();
        } catch (InvalidRecordException ex) {

            log.error(this.toString());
            log.error(ex);
            log.error(ex.getStackTrace());
        }

        if (iterable != null) {
            ((IEntityAmount) iterable).moltiplicaImporti();
            ((IEntityAmount) iterable).troncaImporti();
            valori.add(iterable);
            valoriLetti += 1;

            // if (iterable.iterator().hasNext()) {
            // valori.add(leggiValori(iterable));
            // valoriLetti += 1;
            // }
        } else {
            break;
        }
    }

Solution

  • This answer explains how you can cast a Collection<A> to Collection<B>: https://stackoverflow.com/a/1651086/1428461