Skip to content

Conditional expression in body of lambda #7029

@smillst

Description

@smillst

Originally posted by @MichalStehlikCz in #7019

Other testcase for probably same problem

public class Test {

  private record Item (
    @Nullable String id) {
  }

  Map<String, Item> test(Collection<Item> source) {
    return source.stream()
        .flatMap(item -> {
          var id = item.id();
          return (id == null)
              ? Stream.empty()
              : Stream.of(Map.entry(id, item));
        })
        .collect(
            Collectors.toUnmodifiableMap(
                entry -> entry.getKey(),
                entry -> entry.getValue()));
  }
}

workaround is to explicitly specify type parameters in BOTH branches of ? expression

public class Test {

  private record Item (
    @Nullable String id) {
  }

  Map<String, Item> test(Collection<Item> source) {
    return source.stream()
        .flatMap(item -> {
          var id = item.id();
          return (id == null)
              ? Stream.<Map.Entry<String, Item>>empty()
              : Stream.<Map.Entry<String, Item>>of(Map.entry(id, item));
        })
        .collect(
            Collectors.toUnmodifiableMap(
                entry -> entry.getKey(),
                entry -> entry.getValue()));
  }
}

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions