@ SuppressWarnings ( "checkstyle:rightCurly" ) static < T > ImmutableList < T > sortMostSpecificFirst ( final Iterable < T > classes , final Function < T , Class < ? > > toClass ) { final List < T > working = Lists . newArrayList ( ) ; // strip duplicates for ( final T t : classes ) { if ( ! working . contains ( t ) ) { working . add ( t ) ; } } final List < T > sorted = Lists . newArrayList ( ) ; final Predicate < T > mostSpecific = createMostSpecificMatchPredicate ( working , toClass ) ; boolean changed = false ; do { changed = false ; for ( final Iterator < T > iterator = working . iterator ( ) ; iterator . hasNext ( ) ; ) { final T t = iterator . next ( ) ; if ( mostSpecific . apply ( t ) ) { sorted . add ( t ) ; iterator . remove ( ) ; changed = true ; } } } while ( changed ) ; if ( ! working . isEmpty ( ) ) { throw new IllegalStateException ( "Unable to find a element that does not have a more specific element in the set " + working ) ; } return ImmutableList . copyOf ( sorted ) ; }
Returns a Immutable List sorted with the most specific associated class first . Each element is guaranteed to not be assignable to any element that appears before it in the list .