从两个具有相似对象ID的列表中获取地图

我是java流API的新手。 我有2个列表,并且如果两个内部对象ID都匹配,则希望将某些属性添加到MAP。 下面是实现。


List<LookupMstEntity> examTypeDetails; //This list contains values init.
List<MarksMstEntity> marksDetailList;  //This list contains values init.

//FYI above entities have lombok setter, getter, equals & hashcode.

Map<Long, Integer> marksDetailMap = new HashMap<>();

//need below implementation to changed using java 8.
for(LookupMstEntity examType : examTypeDetails)
{
    for(MarksMstEntity marks : marksDetailList)
    {
        if(examType.getLookupId() == marks.getExamTypeId())
            marksDetailMap.put(examType.getLookupId(), marks.getMarks());
    }
}
评论
eet
eet

First create a set of lookupIds Set<Long> ids then filter marksDetailList accordingly with examTypeId values.

尝试这个:

Set<Long> ids = examTypeDetails.stream().map(LookupMstEntity::getLookupId).collect(Collectors.toSet());

Map<Long, Integer> marksDetailMap = marksDetailList.stream().filter(m -> ids.contains(m.getExamTypeId()))
    .collect(Collectors.toMap(MarksMstEntity::getExamTypeId, MarksMstEntity::getMarks));
点赞
评论