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

Time:04-29

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

CodePudding user response:

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;
}

CodePudding user response:

I used lambda's to construct the Comparators. I believe, based on the comments, this is what you wanted.

Comparator<String> roleComparator = (o1,o2)->
          o1.isBlank() && o2.isBlank() ? 0 :
              o1.isBlank() ? 1 : o2.isBlank() ? -1 : 0;

Comparator<User> comp = Comparator.comparing(User::getRole, 
      roleComparator).thenComparing(
                User::getJoinedDate, dateComparator);

You can specify comp as the sort comparator.

I tested this using a selection sort, which is known to be unstable, by shuffling a list using both a stable (Collections.sort) and the selection sort and comparing the results. But still, an unstable sort will not always exhibit instability.

  • Related