How to get a Map owned by an Object as an attribute from a List of these objects

651 views Asked by At

I have an BOLReference object as follows:

private String ediTransmissionId;
private List<WorkflowExceptions> workflowExceptions;

And the inner WorkflowExceptions looks like below:

private String category;
private Map<String,String> businessKeyValues;

I want to get a particular Map<String,String> businessKeyValues from the list of WorkflowExceptions based on some filters. How can I do so?

        Map<String,String> bKeyMap = bolRef.get(0).getWorkflowExceptions()
            .stream().filter(wk->wk.getBusinessKeyValues().containsKey("ABC123"));
1

There are 1 answers

0
Alexander Ivanchenko On BEST ANSWER

In order to obtain the map businessKeyValues that contains a certain key, first, you need to apply map() operation to extract the map from a WorkflowExceptions object.

Then apply filter() operation as you've done in your code. And findFirst() (which returns the first encountered element in the stream) as a terminal operation.

Method findFirst() returns an optional object, because the result may or may not be present in the stream. Optional class offers you a wide variety of methods that allow to treat the situation when result is not present in different ways depending on your needs. Down below I've used orElse() method that'll provide an empty map if result wasn't found.

Other options you might consider: orElseThrow(), orElseGet(), or() (in conjunction with other methods).

Map<String,String> bKeyMap = bolRef.get(0).getWorkflowExceptions()
                .stream()
                .map(WorkflowExceptions::getBusinessKeyValues)
                .filter(bkv -> bkv.containsKey("ABC123"))
                .findFirst()
                .orElse(Collections.emptyMap());