Java 两个ArrayList/List对象的排序

Java 两个ArrayList/List对象的排序,java,arrays,sorting,arraylist,Java,Arrays,Sorting,Arraylist,例如,我将两个数组转换为ArrayList,即firstName和lastName。我想用名字对这两个列表进行排序,名字后面跟着姓氏 预期产出: firstNameList = {Andrew, Johnson, William} lastNameList = {Wiggins, Beru, Dasovich}; 我最初的计划: import java.util.Arrays; import java.util.ArrayList; import java.util.Collections;

例如,我将两个数组转换为ArrayList,即firstName和lastName。我想用名字对这两个列表进行排序,名字后面跟着姓氏

预期产出:

firstNameList = {Andrew, Johnson, William}
lastNameList = {Wiggins, Beru, Dasovich};
我最初的计划:

import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collections;

String [] firstName = {William, Johnson, Andrew};
String [] lastName = {Dasovich, Beru, Wiggins};

//Will convert arrays above into list.
List <String> firstNameList= new ArrayList<String>();
List <String> lastNameList= new ArrayList<String>();

//Conversion
Collections.addAll(firstNameList, firstName);
Collections.addAll(lastNameList, lastName);
导入java.util.array;
导入java.util.ArrayList;
导入java.util.Collections;
String[]firstName={William,Johnson,Andrew};
字符串[]lastName={Dasovich,Beru,Wiggins};
//将上面的数组转换为列表。
List firstNameList=newarraylist();
List lastNameList=new ArrayList();
//转化
Collections.addAll(firstNameList,firstName);
Collections.addAll(lastNameList,lastName);
String[]firstNames={William,Johnson,Andrew};
字符串[]lastNames={Dasovich,Beru,Wiggins};
//将上面的数组转换为列表。
List firstNameList=newarraylist();
List lastNameList=new ArrayList();
Map lastNameByFirstName=新HashMap();
for(int i=0;i
String[]firstNames={William,Johnson,Andrew};
字符串[]lastNames={Dasovich,Beru,Wiggins};
//将上面的数组转换为列表。
List firstNameList=newarraylist();
List lastNameList=new ArrayList();
Map lastNameByFirstName=新HashMap();
for(int i=0;i
您可以通过将两个数组合并为一个名称流来实现这一点,包括名字和姓氏,对该流进行排序,然后重新创建两个列表

    String[] firstName = {"William", "Johnson", "Andrew"};
    String[] lastName = {"Dasovich", "Beru", "Wiggins"};

    final var sortedNames = IntStream.range(0, firstName.length)
            .mapToObj(i -> new Name(firstName[i], lastName[i]))
            .sorted(Comparator.comparing(n -> n.firstName))
            .collect(Collectors.toList());

    final var sortedFirstNames = sortedNames.stream()
            .map(n -> n.firstName)
            .collect(Collectors.toList());
    final var sortedLastNames = sortedNames.stream()
            .map(n -> n.lastName)
            .collect(Collectors.toList()); 

您可以通过将两个数组合并为一个名称流来实现这一点,包括名字和姓氏,对该流进行排序,然后重新创建两个列表

    String[] firstName = {"William", "Johnson", "Andrew"};
    String[] lastName = {"Dasovich", "Beru", "Wiggins"};

    final var sortedNames = IntStream.range(0, firstName.length)
            .mapToObj(i -> new Name(firstName[i], lastName[i]))
            .sorted(Comparator.comparing(n -> n.firstName))
            .collect(Collectors.toList());

    final var sortedFirstNames = sortedNames.stream()
            .map(n -> n.firstName)
            .collect(Collectors.toList());
    final var sortedLastNames = sortedNames.stream()
            .map(n -> n.lastName)
            .collect(Collectors.toList()); 

正如评论中所强调的,您的问题是您使用了两个不同的名称和姓氏列表,因此这两种数据类型的排序过程完全不相关。一种可能的解决方案是创建一个新的类
Person
,包括两个字段
name
姓氏
,并实现如下所示的
Comparable
接口:

public class Person implements Comparable<Person> {
    public String firstName;
    public String lastName;

    public Person(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    @Override
    public String toString() {
        return "Person [firstName=" + firstName + ", lastName=" + lastName + "]";
    }

    @Override
    public int compareTo(Person o) {
        return this.firstName.compareTo(o.firstName);
    }

    public static void main(String[] args) {
        Person[] persons = { new Person("William", "Dasovich"),
                             new Person("Johnson", "Beru"),
                             new Person("Andrew", "Wiggins") };

        Collections.sort(Arrays.asList(persons));
        for (Person person : persons) {
            System.out.println(person);
        }
    }
}
公共类人员实现可比较{
公共字符串名;
公共字符串lastName;
公众人物(字符串名、字符串名){
this.firstName=firstName;
this.lastName=lastName;
}
@凌驾
公共字符串toString(){
返回“Person[firstName=“+firstName+”,lastName=“+lastName+””;
}
@凌驾
公共内部比较(o人){
返回this.firstName.compareTo(o.firstName);
}
公共静态void main(字符串[]args){
人[]人={新人(“威廉”,“达索维奇”),
新人(“约翰逊”、“贝鲁”),
新人(“安德鲁”、“威金斯”)};
Collections.sort(Arrays.asList(persons));
用于(人:人){
系统输出打印项次(人);
}
}
}

Collections.sort
方法按
firstName
提供了
Person
数组的顺序。正如注释所强调的,您的问题是,您对姓名和姓氏使用了两个不同的列表,因此这两种数据类型的排序过程完全不相关。一种可能的解决方案是创建一个新的类
Person
,包括两个字段
name
姓氏
,并实现如下所示的
Comparable
接口:

public class Person implements Comparable<Person> {
    public String firstName;
    public String lastName;

    public Person(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    @Override
    public String toString() {
        return "Person [firstName=" + firstName + ", lastName=" + lastName + "]";
    }

    @Override
    public int compareTo(Person o) {
        return this.firstName.compareTo(o.firstName);
    }

    public static void main(String[] args) {
        Person[] persons = { new Person("William", "Dasovich"),
                             new Person("Johnson", "Beru"),
                             new Person("Andrew", "Wiggins") };

        Collections.sort(Arrays.asList(persons));
        for (Person person : persons) {
            System.out.println(person);
        }
    }
}
公共类人员实现可比较{
公共字符串名;
公共字符串lastName;
公众人物(字符串名、字符串名){
this.firstName=firstName;
this.lastName=lastName;
}
@凌驾
公共字符串toString(){
返回“Person[firstName=“+firstName+”,lastName=“+lastName+””;
}
@凌驾
公共内部比较(o人){
返回this.firstName.compareTo(o.firstName);
}
公共静态void main(字符串[]args){
人[]人={新人(“威廉”,“达索维奇”),
新人(“约翰逊”、“贝鲁”),
新人(“安德鲁”、“威金斯”)};
Collections.sort(Arrays.asList(persons));
用于(人:人){
系统输出打印项次(人);
}
}
}

Collections.sort
方法通过
firstName
提供
Person
数组的顺序,因为
firstName
lastName
是相互连接的,所以您应该创建一个类来对它们进行建模。让我们把这个类称为Person

class Person {
    private final String firstName;
    private final String lastName;

    public Person(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }

    // Add toString, equals and hashCode as well.
}
现在,创建一个人员列表:

List<Person> persons = Arrays.asList(
    new Person("Andrew", "Wiggins"),
    new Person("Johnson", "Beru"),
    new Person("William", "Dasovich"));

因为
firstName
lastName
是相互连接的,所以应该创建一个类来对它们进行建模。让我们把这个类称为Person:

class Person {
    private final String firstName;
    private final String lastName;

    public Person(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }

    // Add toString, equals and hashCode as well.
}
现在,创建一个人员列表:

List<Person> persons = Arrays.asList(
    new Person("Andrew", "Wiggins"),
    new Person("Johnson", "Beru"),
    new Person("William", "Dasovich"));
树集可以做到这一点:
(使用Turing85建议的Person类)

树集可以做到这一点:
(使用Turing85建议的Person类)

String[]firstName={“威廉”、“约翰逊”、“安德鲁”};
字符串[]lastName={“Dasovich”、“Beru”、“Wiggins”};
//组合这两个数组并将全名添加到数组列表中
//这里使用一个特殊的字符进行组合,以便我们以后可以使用相同的字符进行拆分
//例如,“威廉·达索维奇”
List combinedList=新的ArrayList();
斯特林
    String[] firstName = {"William", "Johnson", "Andrew"};
    String[] lastName = {"Dasovich", "Beru", "Wiggins"};

    // combine the 2 arrays and add the full name to an Array List 
    // here using a special character to combine, so we can use the same to split them later
    // Eg. "William # Dasovich"
    List<String> combinedList = new ArrayList<String>();
    String combineChar = " # ";        
    for (int i = 0; i < firstName.length; i++) {
        combinedList.add(firstName[i] + combineChar + lastName[i]);
    }
    // Sort the list 
    Collections.sort(combinedList);

    // create 2 empty lists
    List<String> firstNameList = new ArrayList<String>();
    List<String> lastNameList = new ArrayList<String>();

    // iterate the combined array and split the sorted names to two lists
    for (String s : combinedList) {
        String[] arr = s.split(combineChar);
        firstNameList.add(arr[0]);
        lastNameList.add(arr[1]);
    }
    System.out.println(firstNameList);
    System.out.println(lastNameList);
 String[] firstName = {"William", "Johnson", "Andrew"};
 String[] lastName = {"Dasovich", "Beru", "Wiggins"};

//Will convert arrays above into list.
        List<String> firstNameList = new ArrayList<String>();
        List<String> lastNameList = new ArrayList<String>();

//Conversion
        Collections.addAll(firstNameList, firstName);
        Collections.addAll(lastNameList, lastName);

        List<String> collect = firstNameList
                .stream()
                .map(name -> {
                    List<String> couple = List.of(name, lastNameList.get(0));
                    lastNameList.remove(0);
                    return couple;
                })
                .sorted(Comparator.comparing(l -> l.get(0)))
                .flatMap(Collection::stream)
                .collect(Collectors.toList());
class Person {
    public static final String PERSON_TO_STRING_FORMAT = "{f: %s, l: %s}";

    private final String firstName;
    private final String lastName;

    private Person(final String firstName, final String lastName) {
        this.firstName = Objects.requireNonNull(firstName);
        this.lastName = Objects.requireNonNull(lastName);
    }

    public static Person of(final String firstName, final String lastName) {
        return new Person(firstName, lastName);
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }

    @Override
    public String toString() {
        return String.format(PERSON_TO_STRING_FORMAT, getFirstName(), getLastName());
    }
}
    public static List<Person> constructPersons(
            final String[] firstNames,
            final String[] lastNames) {
        if (firstNames.length != lastNames.length) {
            throw new IllegalArgumentException("firstNames and lastNames must have same length");
        }
        return IntStream.range(0, firstNames.length)
                .mapToObj(index -> Person.of(firstNames[index], lastNames[index]))
                .collect(Collectors.toCollection(ArrayList::new));
    }
public class Person implements Comparable<Person> {
    ...
    @Override
    public final int compareTo(final Person that) {
        if (Objects.equals(getFirstName(), that.getFirstName())) {
            return getLastName().compareTo(that.getLastName());
        }
        return getFirstName().compareTo(that.getFirstName());
    }
    ...
}
public class Person implements Comparable<Person> {
    ...
    @Override
    public final boolean equals(Object thatObject) {
        if (this == thatObject) {
            return true;
        }
        if (thatObject == null || getClass() != thatObject.getClass()) {
            return false;
        }
        final Person that = (Person) thatObject;
        return Objects.equals(getFirstName(), that.getFirstName()) &&
                Objects.equals(getLastName(), that.getLastName());
    }

    @Override
    public final int hashCode() {
        return Objects.hash(getFirstName(), getLastName());
    }
    ...
}
final List<Person> persons = constructPersons(
        new String[]{"Clair", "Alice", "Bob", "Alice"},
        new String[]{"Clear", "Wonder", "Builder", "Ace"}
);
Collections.sort(persons);
System.out.println(persons);
class PersonByFirstNameThenByLastNameComparator implements Comparator<Person> {
    public static final PersonByFirstNameThenByLastNameComparator INSTANCE =
            new PersonByFirstNameThenByLastNameComparator();

    private PersonByFirstNameThenByLastNameComparator() {}

    @Override
    public int compare(final Person lhs, final Person rhs) {
        if (Objects.equals(lhs.getFirstName(), rhs.getFirstName())) {
            return lhs.getLastName().compareTo(rhs.getLastName());
        }
        return lhs.getFirstName().compareTo(rhs.getFirstName());
    }
}
final List<Person> persons = constructPersons(
        new String[]{"Clair", "Alice", "Bob", "Alice"},
        new String[]{"Clear", "Wonder", "Builder", "Ace"}
);
persons.sort(PersonByFirstNameThenByLastNameComparator.INSTANCE);
System.out.println(persons);
Comparator.comparing(Person::getFirstName).thenComparing(Person::getLastName)
final List<Person> persons = constructPersons(
        new String[]{"Clair", "Alice", "Bob", "Alice"},
        new String[]{"Clear", "Wonder", "Builder", "Ace"}
);
persons.sort(Comparator.comparing(Person::getFirstName).thenComparing(Person::getLastName));
System.out.println(persons);