I am trying to sort a list in a specific way in Java, and I found that Comparator
is a good way to do so.
I will share with you a pseudo code of the problem.
I have a list of DTOs and let's say I want to sort it by a property(String) in a specific order, for example properties starting with "Hi"
should be on top and the rest should be below.
Here is my pseudo code :
list.sort(new Comparator<myDto>(){
@Override
public int compare(myDto o1, myDto o2){
if(o1.getProperty1() != null && o2.getProperty1() == null)
return -1;
else if(o1.getProperty1() == null && o2.getProperty1() != null)
return 1;
else if(o1.getProperty1().startsWith("Hi") && o2.getProperty1().startsWith("Hi"))
return 0;
else if(o1.getProperty1().startsWith("Hi") && !o2.getProperty1().startsWith("Hi"))
return -1;
return 1;
}
});
I used like 4, 5 DTO's I created myself to test, but when I inject a file of 14k DTO's I get a java.lang.illegalArgumentException
.
Any ideas ?