0

I want to sort an ArrayList of Objects

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.

Karol Dowbecki
45.2k9 gold badges82 silver badges118 bronze badges
asked Jul 11, 2017 at 9:40
2
  • 4
    What have you tried so far? Do you know how to use comparators? Commented 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. Commented Jul 11, 2017 at 9:53

3 Answers 3

1

A possible Java 8 solution:

nameArray.sort(Comparator.comparingInt(name -> {
 int index = numberArray.indexOf(name.id);
 return index == -1 ? Integer.MAX_VALUE : index;
 }));
answered Jul 11, 2017 at 9:53

Comments

0

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.

answered Jul 11, 2017 at 9:51

Comments

0

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]]
answered Jul 11, 2017 at 10:05

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.