Home > Back-end >  Merging Object and List with Lambdas
Merging Object and List with Lambdas

Time:02-08

I have a situation similar to the follows:

List<ObjectA> all = repository.findAll(Sort.by(Sort.Direction.ASC, "status"));

This find a list of object with three possible states: OPEN, CLOSED, PROGRAMMED

Now I must return a List that shows to the user the last PROGRAMMED object, the first OPEN object and all closed objects. I have writing something like that:

ObjectA programmed = all.stream().filter(isPROGRAMMED()).reduce((x,y) -> y).orElse(null);
ObjectA open = all.stream().filter(isOPEN()).findFirst().get();
List<ObjectA> closed = all.stream().filter(isCLOSED()).collect(Collectors.toList());

isOPEN(), isPROGRAMMED() and isCLOSED() are Predicate I have written as follows:

private static Predicate<ObjectA> isPROGRAMMED() {
    return x -> x.getStatus().equals(Stato.PROGRAMMED);
}

private static Predicate<ObjectA> isOPEN() {
    return x -> x.getStatus().equals(Stato.OPEN);
}

private static Predicate<ObjectA> isCLOSED() {
    return x -> x.getStatus().equals(Stato.CLOSED);
}

Now I want just to merge the two object and the third list into one. List should contain programmed item (if present) open object (if present) and after that all closed items. I jave tried with Stream.of, Stream.concat but I always obtain some compilation errors..

Are there some way to do it with Lambdas and with few code? Thank you

CodePudding user response:

If you want to avoid mutation of the closed list, then Stream IPA is one of the possible choices for this task.

It could be done like this:

    public static List<ObjectA> merge(List<ObjectA> closed, ObjectA programmed, ObjectA open) {
        return Stream.concat(Stream.of(programmed, open), 
                             closed.stream())
                .collect(Collectors.toList());
    }

And as I've already mentioned in the comment if are not concerned about preserving the initial state of the closed list, then these objects can be added directly to the list:

        closed.add(0, open);
        closed.add(0, programmed);

Side note:

  • There's an inconsistency in how you are obtaining a programmed object and open object. If a programmed object doesn't exist your decided to return null. But if there's no open object, method get() will raise NoSuchElementException.
ObjectA programmed = all.stream().filter(isPROGRAMMED()).reduce((x,y) -> y).orElse(null);
ObjectA open = all.stream().filter(isOPEN()).findFirst().get();
  •  Tags:  
  • Related