Home > front end >  How to compare nested objects
How to compare nested objects

Time:02-02

I am trying to sort a list of LeaveRequest by it's User name, but it is not working. The resulting list is not ordered based on User's name and it seems not to be affected by the sorted() method.

Here is the comparing code I am using:

leaveRequests = leaveRequests.stream()
     .sorted(Comparator.comparing(x -> x.getUser().getName()))
     .collect(Collectors.toList());

Here is LeaveRequest class:

@Entity
@Table
public class LeaveRequest implements Serializable {

    @Id
    @GeneratedValue
    private long id;

    @ManyToOne(optional = false)
    @NotNull
    @JoinColumn(name = "user_id")
    private User user;

    ... getter and setter
}

and the User class:

@Entity
@Table(name = "\"user\"")
public class User implements Serializable {

@Id
@GeneratedValue
private long id;

@Column(nullable = false)
@NotNull
@Size(min = 1, max = 100)
private String name;

... getter and setter
}

CodePudding user response:

String comparisons are performed based on lexicographic (ascii/unicode) order, which is not the same as alphabetic order (aka dictionary order), and may not localize well without some amount of fiddling.

For instance, if you're running into an issue where, for instance, lowercase and uppercase letters aren't sorted correctly (for instance, you want the order dginzberg - Fyruz - Mark Rotteveel - rzwitserloot - user16320675 but instead you got dginzberg - rzwitserloot - user16320675 - Fyruz - Mark Rotteveel That would be because capital and lowercase letters are treated as different characters in the ascii and unicode systems.

If that's the issue you were running into, you might want to look at using case insensitive sorting to sort your stream. This would be a small change so your comparator line includes a function in your comparator, as documented in the Java API here. Probably something like the snippet below:

leaveRequests = leaveRequests.stream()
     .sorted(Comparator.comparing(x -> x.getUser().getName(), String.CASE_INSENSITIVE_ORDER))
     .collect(Collectors.toList());

CodePudding user response:

You could have your LeaveRequest class implement comparable and compare.by user name.. Then simple list.stream.sorted then collect would suffice.

  •  Tags:  
  • Related