无法在原始类型 void 上调用 forEach((<no type> de) -> {})

我有一个元素列表,我想在 forEach 元素中创建一个构造函数,但出现错误:无法在原始类型 void 上调用 forEach(( de) -> {})


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);


    }


蓝山帝景
浏览 118回答 2
2回答

缥缈止盈

该findAllByMatch方法正在返回一个List<MatchEvent>.并且该List.sort(someComparator)方法返回void,即它不返回任何内容,因为它就地对列表进行排序。所以你不能将调用链接到forEach(someConsumer).解决您的问题的一种方法是使用 aStream而不是 a List:List<MatchEventMobileApp> matchEventMobileApp = matchEventService&nbsp; &nbsp; .findAllByMatch(SOME_MATCH)&nbsp; &nbsp; &nbsp; &nbsp; .stream()&nbsp; &nbsp; &nbsp; &nbsp; .sorted(Comparator.comparing(MatchEvent::getDateReceived))&nbsp; &nbsp; &nbsp; &nbsp; .map(de -> new MatchEventMobileApp(de)) // or MatchEventMobileApp::new&nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.toList()); // better collect to a new list instead of&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// adding to an existing one within forEach这样一来,你现在有工作Stream,其sorted方法返回另一个Stream(已排序的),可以在其上调用终端操作,即collect,forEach,anyMatch等等。另一种可能性是将列表提取到变量中并使用它:List<MatchEvent> list = matchEventService.findAllByMatch(SOME_MATCH);list.sort(Comparator.comparing(MatchEvent::getDateReceived));list.forEach(de -> matchEventMobileApp.add(new MatchEventMobileApp(de)));

莫回无

List<MatchEventMobileApp>&nbsp;matchEventMobileApp&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;=&nbsp;matchEventService &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.findAllByMatch(“JVT”) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.stream() &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.sorted(Comparator.comparing(MatchEvent::getDateReceived)) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.map(MatchEventMobileApp::new) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.collect(Collectors.toList());
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java