I want to sort an ArrayList
of Object
s
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}
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}
Can you please help me to do this using Java's Comparator
.
-
4What have you tried so far? Do you know how to use comparators?Turtle– Turtle2017年07月11日 09:41:39 +00:00Commented Jul 11, 2017 at 9:41
-
I know to use comparators when we need sort values of Array. i am not so clear about how to campare an array using another array.Sharan Rai– Sharan Rai2017年07月11日 09:53:01 +00:00Commented Jul 11, 2017 at 9:53
3 Answers 3
A possible Java 8 solution:
nameArray.sort(Comparator.comparingInt(name -> {
int index = numberArray.indexOf(name.id);
return index == -1 ? Integer.MAX_VALUE : index;
}));
Comments
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. 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.
Comments
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]]