简体   繁体   中英

Compiler error in stream / flatMap using JDK 11

I upgraded from JDK 1.8.0_212 to JDK 11.0.4 and the following code is not working anymore.

Map<String, Object> results = new HashMap<>();

Object obj = results.values().stream()
        .map(o -> (List) o)
        .flatMap(List::stream)
        .map(o -> (Map) o)
        .map(e -> e.get("id"));

In Java 11 it gives this error on the last line of code:

Error:(13, 24) java: cannot find symbol
  symbol:   method get(java.lang.String)
  location: variable e of type java.lang.Object

It seems to be caused by the flatMap because this re-arranged code works fine:

Object obj = results.values().stream()
        .map(o -> (Map) o)
        .map(e -> e.get("id"))
        .map(o -> (List) o)
        .flatMap(List::stream);

Any ideas why it works in Java 8 but it doesn't in Java 11? What is the change I need to make in Java 11?

Add types for the type variables in the generic types ( List and Map ). So you will not need any type casts and it will compile. Although the code may work unter Java 8 it is hard to understand and to maintain without the types. It will look something like this:

Map<String, List<Map<String, Object>>> results = new HashMap<>();

Object obj = results.values().stream()
      .flatMap(List::stream)
      .map(e -> e.get("id"));

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