1
 Boolean isSuccess = true;
    if(aMap.size() != bMap.size())
    {
        return false;
    }

    aMap.entrySet().forEach(entry -> {
        AKey aKey = entry.getKey();
        BValue bValue = bMap.get(aKey);

        if(bValue == null)
            return;

        AValue aValue = entry.getValue();
        if(!aValue.getClosed().equals(bValue.getClosed()))
            return;

        if(!aValue.getClosedToArrival().equals(bValue.getClosedToArrival()))
            return;

        if(!aValue.getClosedToDeparture().equals(bValue.getClosedToDeparture()))
            return;

        if(!aValue.getLengthOfStayArrival().equals(bValue.getLengthOfStayArrival()))
            return;
    });

    return isSuccess;

How can i return false when validation failure? i tried to add return false, such as below:

if(!aValue.getLengthOfStayArrival().equals(bValue.getLengthOfStayArrival()))
        return false; 

but it is unexpected expression, who can help me have a look?

Haven Lin
  • 176
  • 1
  • 16
  • 4
    By not using `forEach`. When you want to check whether all elements fulfill a condition, you want to use `allMatch`. By the way, you can change your pretest to `if(!aMap.keySet().equals(bMap.keySet()) return false;` This checks more than the size of the map and allows to omit the `null` test in your condition. – Holger Apr 27 '17 at 12:35
  • thank you for your quick response – Haven Lin Apr 27 '17 at 12:39
  • @Holger Hi, Could you help to answer a question for http://stackoverflow.com/questions/43973596/how-to-convert-foreach-to-lambda – Haven Lin May 15 '17 at 07:27

1 Answers1

5

You can't return false because you are in a lambda expression which implement the Consumer functional interface which method is of void type.

Instead, use anyMatch or noneMatch or allMatch :

return aMap.entrySet().stream().anyMatch(entry -> {
    return false;// Put your condition here 
});

I would also recommend to extract the validation in a method so that your pipeline looks like this :

return aMap.entrySet()
           .stream()
           .anyMatch(this::checkIfMatch);

Most of the times when opening {}, it's a good sign that you should create a new method.

Jean-François Savard
  • 20,626
  • 7
  • 49
  • 76
  • 2
    well, in this case you can rewrite the expression to a form without the braces, i.e. `x -> condition1 && condition2 && condition3 …`, but it’s still so big that using a dedicated method is recommend, especially as it would have a more general purpose, comparing `AValue` and `BValue` objects, which might be useful at other places too. – Holger Apr 27 '17 at 12:41