简体   繁体   English

根据另一个数组对对象的ArrayList进行排序-Java

[英]Sort ArrayList of Objects based on another array - Java

I want to sort an ArrayList of Object s 我想对ObjectArrayList进行排序

nameArray = {[id:109,name:"abc"],[id:103,name:"bcd"],[id:105,name:"efg"],[id:102,name:"hij"],[id:111,name:"klm"]} nameArray = {[id:109,name:"abc"],[id:103,name:"bcd"],[id:105,name:"efg"],[id:102,name:"hij"],[id:111,name:"klm"]}

using another array 使用另一个数组

numberArray = {103,111} numberArray = {103,111}

now I want my sorted array to have values in the order 现在我希望我的排序数组具有顺序中的值

arrayAfterSort = {[id:103,name:"bcd"],[id:111,name:"klm"],... no matter other values in array can be of any order} arrayAfterSort = {[id:103,name:"bcd"],[id:111,name:"klm"],... no matter other values in array can be of any order}

Can you please help me to do this using Java's Comparator . 您能否使用Java的Comparator帮助我做到这一点。

A possible Java 8 solution: 可能的Java 8解决方案:

nameArray.sort(Comparator.comparingInt(name -> {
        int index = numberArray.indexOf(name.id);
        return index == -1 ? Integer.MAX_VALUE : index;
    }));

This can be achieved using a custom comparator. 这可以通过使用自定义比较器来实现。

nameArray.sort(Comparator.comparing(MyClass::getId, numberArray::indexOf)).

Because indexOf returns -1 if it can't find a value those items will be first in the list. 因为indexOf如果找不到值, indexOf返回-1,因此这些项将在列表中排在第一位。 Your question said that their order doesn't matter but if you do want to force them to be last, or sort by some other criteria then, for example: 您的问题是,它们的顺序无关紧要,但是如果您确实要强迫它们排在最后,或者按照其他条件排序,例如:

nameArray.sort(Comparator.comparing(MyClass::getId, numberArray::contains).reversed()
    .thenComparing(MyClass::getId, numberArray::indexOf)
    .thenComparing(MyClass::getName));

The first comparison returns a boolean which has a natural order of false first which needs to be reversed. 第一个比较返回一个布尔值,该布尔值的自然顺序为false,需要颠倒。

Try this. 尝试这个。

List<Name> nameArray = Arrays.asList(
    new Name(109, "abc"),
    new Name(103, "abc"),
    new Name(105, "abc"),
    new Name(102, "abc"),
    new Name(111, "abc"));
List<Integer> numberArray = Arrays.asList(103, 111);
nameArray.sort(Comparator.comparing(n -> {
    int index = numberArray.indexOf(n.id);
    return index >= 0 ? index : Integer.MAX_VALUE;
}));
System.out.println(nameArray);

result: 结果:

[[id:103:name:abc], [id:111:name:abc], [id:109:name:abc], [id:105:name:abc], [id:102:name:abc]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM