Find first matching entry and assign the matching entry value to variable

Viewed 121

In want to assign the value to variable by using filter and find first (to avoid matching rest and saving iteration).

String output = ""

Map<String, Map<String, CustomObj>> finalMap = new LinkedHashMap<>();;

Map<String, CustomObj> isinMap = new HashMap<>();
isinMap.put("REL", new CustomObj("RELIANCE ISIN"));
isinMap.put("AXIS", new CustomObj("AXISBANK ISIN"));

Map<String, CustomObj> cusipMap = new HashMap<>();
cusipMap.put("CREL", new CustomObj("RELIANCE CUSIP"));
cusipMap.put("CAXIS", new CustomObj("AXISBANK CUSIP"));


finalMap.put("ISIN",isinMap);
finalMap.put("CUSIP",cusipMap);


Map<String,String> tradeDetails = new HashMap<>();
tradeDetails.put("ISIN","AXIS");
tradeDetails.put("CUSIP","AXIS2");


finalMap.entrySet().stream().filter(finalMapEntry-> {
String value = tradeDetails.get(finalMapEntry.getKey());
return finalMapEntry.getValue().containsKey(value);

        // I want following
        //output = finalMapEntry.getValue().get(value).get(); //output should be AXISBANK ISIN
    }
).findFirst();

I know findFirst() will return me first entry in Optional but I want the value of inner map key to be assigned to output variable. IS it possible to do it somehow while streaming and also skipping other iterations if match found on first any nth attempt ?

3 Answers

One can make use of the getOrDefault API effectively here as:

String value = tradeDetails.entrySet()
        .stream()
        .map(trade -> finalMap.getOrDefault(trade.getKey(), Collections.emptyMap())
                .get(trade.getValue()))
        .filter(Objects::nonNull)
        .findFirst() // find first non null element (existence in Map as key-value)
        .map(CustomObj::getDesc) // as you need the description
        .orElse("");

You can do like this:

tradeDetails.entrySet().stream()
       .map(entry -> new AbstractMap.SimpleEntry<>(entry.getValue(),
                                                   finalMap.get(entry.getKey())))
       .map(entry -> entry.getValue().get(entry.getKey()))
       .filter(Objects::nonNull)
       .map(CustomObj::getName)
       .findFirst().orElse("");

or

finalMap.entrySet().stream() 
         // .filter(entry -> tradeDetails.keySet().contains(entry.getKey()))
            .map(m -> m.getValue().get(tradeDetails.get(m.getKey())))
            .filter(Objects::nonNull)
            .findFirst()
            .map(CustomObj::getName)
            .orElse("");

Use a map?

Optional<CustomObj> cObjectOpt = finalMap.keySet().stream().filter(k->finalMap.get(k).containsKey(tradeDetails.get(k))).findFirst().map(fk->finalMap.get(fk).get(tradeDetails.get(fk)));
        if(cObjectOpt.isPresent()) {
            System.out.println(cObjectOpt.get().get()); 
        }
Related