简体   繁体   中英

Getting the hashmap values of an object list using lambdas

Lets assume I have an object:

class MyObject {
    private int id;
    private HashMap<Integer, OtherObject> otherObjects;
}

What I want to do is access the otherObjects property of a list of MyObject and add them all to a otherObjects list .

I could use a .forEach and .addAll into the otherObjects list but I'm trying see if it is possible to use lambdas to achieve this. I thought of something like this but it doesn't seem to work:

myObjectList.stream()
    .map(o -> o.getOtherObjects())
    .map(oo -> oo.values())
    .collect(Collectors.toList());

But there seems to be a conflict with the object types. I'm guessing it is because I start with a stream of objects and end up with a stream of lists and it gets confused. How can I achieve this? And more generally, how can I gather a list of objects of many parent objects into a single list?

Use flatMap to fix the signature mismatch. Also prefer method references and win points with Haskell programmers :)

myObjectList.stream()
            .map(MyObject::getOtherObjects)
            .map(Map::values)
            .flatMap(Collection::stream)
            .collect(Collectors.toList());

You can try flatMap:

myObjectList.stream()
            .flatMap(o -> o.getOtherObjects().values().stream())
            .collect(Collectors.toList());

Use the flatMap method instead of the last map call. The flatmap method concatenates the streams that the given function returns, into one stream. Like this:

myObjectList.stream()
    .map(o -> o.getOtherObjects())
    .flatMap(oo -> oo.values().stream())
    .collect(Collectors.toList());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM