Java Collection Sort sortClassesByLevelOfInheritance(Collection> classes)

Here you can find the source of sortClassesByLevelOfInheritance(Collection> classes)

Description

sort Classes By Level Of Inheritance

License

Apache License

Declaration

public static List<Class<?>> sortClassesByLevelOfInheritance(Collection<Class<?>> classes) 

Method Source Code

//package com.java2s;
/*// w  w  w  . j  av  a  2  s .c  o  m
 * Copyright 2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Main {
    public static List<Class<?>> sortClassesByLevelOfInheritance(Collection<Class<?>> classes) {
        List<Class<?>> result = new ArrayList<Class<?>>(classes);
        Collections.sort(result, new Comparator<Class<?>>() {
            public int compare(Class<?> c1, Class<?> c2) {
                int l1 = getLevelOfInheritance(c1);
                int l2 = getLevelOfInheritance(c2);

                if (l1 < l2) {
                    return -1;
                } else if (l1 > l2) {
                    return 1;
                } else {
                    return c1.getName().compareTo(c2.getName());
                }
            }
        });

        return result;
    }

    private static int getLevelOfInheritance(Class<?> c) {
        if (c.getSuperclass() == null) {
            return 1;
        }
        return 1 + getLevelOfInheritance(c.getSuperclass());
    }
}

Related

  1. isSort(Collection c)
  2. sort(Collection collection)
  3. sort(Collection collection, Comparator comparator)
  4. sort(Collection items)
  5. sortByDescendingOrder(Map collection)
  6. sorted(Collection coll)
  7. sorted(Collection input)
  8. sorted(Collection coll)
  9. sorted(Collection collection)