2

I have one list and map, where i need to iterate list first and inside that loop i need to access map to form String message. I have written the same in Java 7 and it works fine. Can someone help in converting this in Java 8 streaming.

        final Map<String, String> destTabMap = ... 
        final List<String> destTabs = mappingList.get(destTabName);

        for (int j=0; j < destTabs.size(); j++) {
            String destName = destTabs.get(j);

            final String fieldValue = destTabMap.get(destName);

            if(fieldValue==null)
                continue;


           message.append(destName+"  ");
           message.append(":");
           message.append("  "+fieldValue);
           message.append("\n");
           System.out.println(destName+"  : "+fieldValue);
        }
1
  • where is mappingList definition? Commented Apr 2, 2019 at 5:13

1 Answer 1

3

You may do it like so,

String resultStr = destTabs.stream()
    .filter(s -> destTabMap.get(s) != null)
    .map(s -> s + "  :  " + destTabMap.get(s))
    .collect(Collectors.joining("\n"));
Sign up to request clarification or add additional context in comments.

2 Comments

Using getOrDefault could make the mapping cleaner.
Consider filtering out absent keys with .filter(destTabMap::containsKey)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.