Search code examples
javacomparator

is there any way we can sort only blanks go last remaining not sort at all in java?


is there any way we can make blank values go last and which are not blank not sort at all. I have requirement like

    userroles-admin,developer,blank field 

I have to sort blanks go last and if incase of admin,developer (which is not blank) they should not sort and it should consider nearest future date to process.

logic i have used:

userList
  .stream()
  .sorted(
     Comparator
       .Comparing(User::getUserRole, roleComparator)
       .thenComparing(user::getJoinedDate, DateComparator))
  .collect(Collectors.toList());
    

so below is the custom comparator for only blanks but its sorting even admin and developer also.

    public class roleComparator implements Comparator<String> {
         @Override
            public int compare(String o1, String o2) {
                if (o1.equals(o2)) {
                    return 0;
                } else if (o1.isBlank()) { 
             
                    return 1;
                }
                return -1;
            }
    
   }
           

when i tried to sort this it is not giving proper order, it should give first not blank values for role and date follows which is nearest future date and as per output here it is taking blank values in last but its taking sorted order as admin first and developer second which should not and giving wrong results. for example:

    1.user("admin","04/30/2022")
    2.user("developer","04/28/2022")
    3.user("developer","04/31/2022")`
    4.user("","04/27/2022")
   

order should be: 2134 but its taking 2314


Solution

  • The problem you have is in your first line, you are comparing strings using String.equals, but that's not what you want. You want all "non-blank" Strings to be equal

    public int compare(String a, String b) 
      if (a.isBlank()) return 1;
      if (b.isBlank()) return -1;
      return 0;
    }