【问题标题】:Cannot invoke forEach((<no type> de) -> {}) on the primitive type void无法在原始类型 void 上调用 forEach((<no type> de) -> {})
【发布时间】:2018-10-21 20:36:14
【问题描述】:

我有一个元素列表,我想在 forEach 元素中创建一个构造函数,但出现错误:Cannot invoke forEach(( de) -> {}) on the original type void

List<MatchEventMobileApp> matchEventMobileApp 
    = new ArrayList<matchEventMobileApp>();


matchEventService
    .findAllByMatch(“JVT”))
        .sort(Comparator.comparing(MatchEvent::getDateReceived))
        .forEach(de -> matchEventMobileApp.add(new MatchEventMobileApp(de)));



public List<MatchEvent> findAllByMatch(Match match) {

        return matchEventRepository.findAllByMatch(match);

    }

【问题讨论】:

  • 我的猜测是findAllByMatch 返回一个List,而List#sort(Comparator) 返回void,因为它就地修改了列表。
  • 请添加findAllByMatch方法签名,@Clashsoft 很可能是正确的

标签: java collections java-8


【解决方案1】:

findAllByMatch 方法返回一个List&lt;MatchEvent&gt;

List.sort(someComparator) 方法返回void,即它什么也不返回,因为它对列表进行就地排序。所以你不能链接到forEach(someConsumer)

您的问题的一个解决方案是使用Stream 而不是List

List<MatchEventMobileApp> matchEventMobileApp = matchEventService
    .findAllByMatch(SOME_MATCH)
        .stream()
        .sorted(Comparator.comparing(MatchEvent::getDateReceived))
        .map(de -> new MatchEventMobileApp(de)) // or MatchEventMobileApp::new
        .collect(Collectors.toList()); // better collect to a new list instead of
                                       // adding to an existing one within forEach

这样,您现在正在使用Stream,其sorted 方法返回另一个Stream(已排序),您可以在其上调用终端操作,即@ 987654332@、forEachanyMatch

另一种可能性是将列表提取到变量并使用它:

List<MatchEvent> list = matchEventService.findAllByMatch(SOME_MATCH);

list.sort(Comparator.comparing(MatchEvent::getDateReceived));

list.forEach(de -> matchEventMobileApp.add(new MatchEventMobileApp(de)));

【讨论】:

    【解决方案2】:
    List<MatchEventMobileApp> matchEventMobileApp 
        = matchEventService
            .findAllByMatch(“JVT”)
            .stream()
            .sorted(Comparator.comparing(MatchEvent::getDateReceived))
            .map(MatchEventMobileApp::new)
            .collect(Collectors.toList());
    

    【讨论】:

      猜你喜欢
      • 2019-01-12
      • 1970-01-01
      • 2013-11-11
      • 2018-11-03
      • 2012-04-15
      • 1970-01-01
      • 2014-05-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多