1

I have array list with long ids

Arrays.asList(12, 34, 54, 22, 33);

I have an Object with OwnerClass(String description, long id);

I want to sort the List<OwnerClass> by the index of id in my array list.. so if id is 12 it will be the first and if id is 33 it will be the last.. if the id is not found in the array then put it in the last..

  • 3
    `Collections.sort(ownerClassList, Comperator.comparingInt(o -> longList.indexOf(o.getId()));` You might need to check the result of index of and replace it with `Integer.MAX_VALUE`. – Johannes Kuhn Apr 17 '20 at 06:03
  • @JohannesKuhn can we close this question as such questions already has answer here multiple times. – Amit Kumar Lal Apr 17 '20 at 06:04
  • If you find the duplicate, yes. Also the reason I use a comment. Not worth the time to explain how I know what each piece does and how it relates to the question. – Johannes Kuhn Apr 17 '20 at 06:04
  • @JohannesKuhn may be shortened to `ownerClassList.sort(Comperator.comparingInt(o -> longList.indexOf(o.getId()));` – Lino Apr 17 '20 at 06:45
  • Why is this being upvoted when there is no attempt from OP to solve it? – Joakim Danielson Apr 17 '20 at 10:54

1 Answers1

3

This will work

 final var integers = Arrays.asList(12, 34, 54, 22, 33);

 final var ownerClasses = Arrays.asList(new OwnerClass("", 33), new OwnerClass("", 54), new OwnerClass("", 34), new OwnerClass("", 22), new OwnerClass("", 12));

 ownerClasses.sort(Comparator.comparing(ownerClass -> {var index = integers.indexOf(ownerClass.id); return index != -1 ? index : Integer.MAX_VALUE;}));

Result

[OwnerClass(description=, id=12), OwnerClass(description=, id=34), OwnerClass(description=, id=54), OwnerClass(description=, id=22), OwnerClass(description=, id=33),
OwnerClass(description=,  id=100)]

CodeScale
  • 3,046
  • 1
  • 12
  • 20