Search code examples
javalistcollectionsjava-stream

sort java list by single attribute


I have a Java list of items and those items have a property. This property can be checked with a lambda resulting in true or false. Now I want to sort this list to have all the elements with that property in the front, and all the others in the back.

My current approach is

List<String> frontIds = ... // contains the ids of the items, that I want in front
List<Item> items = ... // contains all the items
List<List<Item>> sortedBy = new ArrayList<>(
  items.stream().collect(
    Collectors.groupingBy(item -> frontIds.contains(item.getId()))
  ).values()
);
sortedBy.get(1).addAll(sortedBy.get(0));

// my sorted list is not sortedBy.get(1)

It does feel a bit bulky and unnecessary to group and create the ArrayList. I thought of using items.sort... but how would I compare just one element with the list of frontIds


Solution

  • You can sort on a boolean. But it can be a little unintuitive because false precedes true, so you have to invert it:

    List<Item> sorted = items.stream()
            .sorted(Comparator.comparing(item -> !frontIds.contains(item.getId()))
            .collect(Collectors.toList());