Java 8 - put light element in a target Map from an other Map

sgrillon :

My code is:

Map<String, Application> applications = new HashMap<>();

// add elements to applications here ...

applications.forEach((key, app) -> { System.out.println(key + " " + app.getHomeUrl()); });

Map<String, String> apps = new HashMap<>();
applications.forEach((key, app) -> { apps.put(key, app.getHomeUrl()); });
metrics.setApplications(apps);

But I looking for how to use a simple filter and not use a toporary Map (apps)?

Console:

xxxx https://xxxx.github.io/xxxx.io
githubapi null
google http://www.google.fr
demo null
yyyy https://yyyy.github.io/yyyy.io
Naman :

One way to avoid creating the apps variable would be

metrics.setApplications(applications.entrySet().stream()
        .filter(e -> e.getValue().getHomeUrl() != null) // filter out entries with null homeUrl
        .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().getHomeUrl())));

where the toMap is collecting the key from the applications Map and the value is mapped to the homeUrl while collecting the respective entries.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=165017&siteId=1