Skip to content
Advertisement

Best way to sort customerAddress in such a way that all primary address are at the top and others at the bottom

I am trying to sort the below list in such a way that primary address is at the top of the list followed by other address (p.getIsPrimary is a Boolean value and can be null). Is there any other way other than below?

List<CustomerAddress> primaryAddress = customerAddresses.stream()
                                       .filter(p->Boolean.TRUE.equals(p.getIsPrimary()))
                                       .collect(Collectors.toList());

List<CustomerAddress> secondaryAddress = customerAddresses.stream().collect(Collectors.toList());

secondaryAddress.removeAll(primaryAddress);
primaryAddress.addAll(secondaryAddress);```

Advertisement

Answer

To sort primary addresses first, call sort() with a Comparator that orders primary addresses before non-primary addresses, e.g.

customerAddresses.sort(Comparator.comparingInt(
        a -> a.getIsPrimary() != null && a.getIsPrimary() ? 0 : 1));

The code sorts by an int value, a kind of “sort order” value, where 0 = primary and 1 = non-primary.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement