Search code examples
javajava-streamoption-type

Filter List to get specific object or else return default


class Home {
    String homeName;
    String properties;
}
List<Home> list = new ArrayList<>();
list.add(new Home("DefaultHome","other"));
list.add(new Home("MyHome","other"));
list.add(new Home("BigHome","other"));

I want to stream this list to find valid home properties or return DefaultHome properties.

So if I do the following, it should return me DefaultHome properties.

list.stream().filter(a -> a.gethomeName().equals("HomeNotFound")).findFirst();

If "HomeNotFound" is not in the list, I should get Object of DefaultHome which is new Home("DefaultHome","other")


Solution

  • Add with an OR a second condition to include your default value, sort by name equals DefaultHome so that it is allways at the end:

    list.stream().filter(a -> a.getHomeName().equals("HomeNotFound") || a.getHomeName().equals("DefaultHome"))
        .sorted(Comparator.comparing(h -> "DefaultHome".equals(h.homeName)))
        .findFirst();