使用 java 8 流基于另一个 List<Object2> 填充 List<Object1>

我有2个List

List<Obligation>,List<ObligationStatus> 结构如下:


public class Obligation {

    private String topic;

    private String status;

    private String comment;

    private String text;

}


public class ObligationStatus {


    private String topic;

    private String status;

    private String comment;

}

status里面是所有元素, 填充在 我想设置的comment和从每个元素到每个元素的基础上。List<Obligation>null

topiclist

statuscommentList<ObligationStatus>List<Obligation>topic


        // this is what i have tried, and is working fine

        obList.stream().forEach(ob -> {

            osList.stream().forEach(os -> {

                if (ob.getTopic().equalsIgnoreCase(os.getTopic())) {

                    ob.setStatus(os.getStatus());

                    ob.setComment(os.getComment());

                }

            });

        });

// also tried to do this without using forEach, but compilation error here

        List<Obligation> result = obList.stream()

                .map(ob -> osList.stream().map(os -> os.getTopic().equals(ob.getTopic())).collect(Function.identity()))

                .collect(Collectors.toList());


我们可以不起诉就这样做吗forEach?

任何信息都会有帮助。


犯罪嫌疑人X
浏览 114回答 2
2回答

30秒到达战场

为什么要为此使用流?Stream 不是改变对象的正确工具。使用标准for循环。也使代码更易于理解。List<Obligation> obligationList = ...;List<ObligationStatus> statusList = ...;// For better performance, make a mapMap<String, ObligationStatus> statusMap = new HashMap<>(statusList.size());for (ObligationStatus status : statusList)&nbsp; &nbsp; statusMap.put(status.getTopic(), status);// Assign status valuesfor (Obligation obligation : obligationList) {&nbsp; &nbsp; ObligationStatus status = statusMap.get(obligation.getTopic());&nbsp; &nbsp; if (status != null) {&nbsp; &nbsp; &nbsp; &nbsp; ob.setStatus(status.getStatus());&nbsp; &nbsp; &nbsp; &nbsp; ob.setComment(status.getComment());&nbsp; &nbsp; }}如果你想做一些流逻辑,第一部分是一个很好的选择:// For better performance, make a mapMap<String, ObligationStatus> statusMap = statusList.stream()&nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.toMap(ObligationStatus::getTopic, Function.identity()));更新注意到问题代码equalsIgnoreCase(...)在比较topic值时做了。如果确实需要,请将 更改HashMap为不区分大小写TreeMap:Map<String, ObligationStatus> statusMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);流版本变得复杂,所以最好保持旧式。

万千封印

由于您正在修改现有的List,因此无需使用collect.但是,您可以使用单个forEach. 可以使用和来定位ObligationStatus与实例匹配的实例。ObligationfilterfindFirstobList.stream().forEach(ob -> {&nbsp; &nbsp; osList.stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .filter(os -> ob.getTopic().equalsIgnoreCase(os.getTopic()))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .findFirst()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .ifPresent (os -> {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ob.setStatus(os.getStatus());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ob.setComment(os.getComment());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java