我有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中的commentList<Obligation>null

在两个topic中都填充了list

我想基于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来做到这一点吗?

任何信息都会有帮助。

最佳答案

为什么要为此使用流?流不是用于更改对象的正确工具。

使用标准的for循环。也使代码更易于理解。

List<Obligation> obligationList = ...;
List<ObligationStatus> statusList = ...;

// For better performance, make a map
Map<String, ObligationStatus> statusMap = new HashMap<>(statusList.size());
for (ObligationStatus status : statusList)
    statusMap.put(status.getTopic(), status);

// Assign status values
for (Obligation obligation : obligationList) {
    ObligationStatus status = statusMap.get(obligation.getTopic());
    if (status != null) {
        ob.setStatus(status.getStatus());
        ob.setComment(status.getComment());
    }
}


如果您想做一些流逻辑,那么第一部分就是一个不错的选择:

// For better performance, make a map
Map<String, ObligationStatus> statusMap = statusList.stream()
        .collect(Collectors.toMap(ObligationStatus::getTopic, Function.identity()));




更新

注意,比较equalsIgnoreCase(...)值时,问题代码没有topic。如果确实需要这样做,请将HashMap更改为不区分大小写的TreeMap

Map<String, ObligationStatus> statusMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);


它的流版本令人费解,因此最好保留其旧样式。

10-06 09:42