如何对具有name属性common的两个不同对象列表进行排序

时间:2017-08-18 18:56:16

标签: java

如何对具有两种不同类型的对象列表属性的对象进行排序。这两个列表都是不同对象的类型。

public class Member {
    private List<Group> groups;
    private List<Person> persons;
}

public class Group {
    private String groupName;
}

public class Person {
    private String personName;
}

是否可以对这两个列表进行排序并获得将根据名称进行排序的组合结果。

expected result
groupName : alex
personName : bob
groupName: christan
groupName: Dan
perosnName: Kat

1 个答案:

答案 0 :(得分:1)

试试这个:

abstract class BaseClass implements Comparable{ // you could name this class as you want
    protected String name;

    @Override
    public int compareTo(Object o) {
        return this.name.compareToIgnoreCase(((BaseClass)o).name);
    }
}

class Group extends BaseClass{
    public Group(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "groupName : " + name;
    }
}

class Person extends BaseClass{
    public Person(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "personName : " + name;
    }
}

然后使用它:

public class Main {

    public static void main(String[] args) {

        List<Group> groups = new ArrayList<>();
        groups.add(new Group("alex"));
        groups.add(new Group("christan"));
        groups.add(new Group("Dan"));

        List<Person> persons = new ArrayList<>();
        persons.add(new Person("bob"));
        persons.add(new Person("Kat"));

        List<BaseClass> members = new ArrayList<>();

        members.addAll(groups);
        members.addAll(persons);
        members.sort(BaseClass::compareTo);

        members.forEach(System.out::println);
    }
}

输出:

  

groupName:alex

     

personName:bob

     

groupName:christan

     

groupName:Dan

     

personName:Kat