我有两个列表List<AreaOfInterest>
和List<AreaOfInterestBean>
。相应的类是
@Entity
@Data
@Table( name = "interest_area" )
public class AreaOfInterest {
@Id
@GeneratedValue( strategy = GenerationType.AUTO )
@Column( name = "ia_id" )
private Long id;
@Column( name = "ia_value" )
private String value;
@Column( name = "ia_is_active" )
private Boolean isActive;
@Column( name = "ia_created_at" )
private Calendar createdAt;
@Column( name = "ia_is_approved" )
private Boolean isApprovedByAdmin;
@Column( name = "ia_approved_at" )
private Calendar approvedAt;
}
和
@Data
public class AreaOfInterestBean {
private Long id;
private String value;
private boolean isSelected;
}
我想检查List<AreaOfInterest>
中是否存在List<AreaOfInterestBean>
的对象,如果存在,则需要更新List<AreaOfInterestBean>
的相应对象。现在,我觉得我必须遍历两个列表才能解决此问题。有什么有效的方法吗?
答案 0 :(得分:2)
说实话,我不确定这个过程的复杂性(我明天会尝试解决):
Set<String> left = nonBeans.stream()
.map(AreaOfInterest::getValue)
.collect(Collectors.toSet());
beans.stream()
.filter(x -> left.contains(x.getValue()))
.forEach(x -> x.setSelected(true));
在这种情况下,复杂度将为O(n)
。
答案 1 :(得分:0)
假设:
List<AreaOfInterest> list = /* ... */
List<AreaOfInterestBean> listOfBeans = /* ... */
只需两个简单的迭代即可轻松实现:
for (int i=0; i<listOfBeans.size(); i++) { // Iterate beans
AreaOfInterestBean aoiBean = listOfBeans.get(i); // Get each bean
for (int j=0; j<list.size(); j++) { // Iterate entity
AreaOfInterest aoi = list.get(j); // Get each entity
if (aoiBean.getId() == aoi.getId()) { // If they have the same ID
aoiBean.setValue(aoi.getValue()); // Update the bean value
break; // Go to the next bean
}
}
}
示例:具有以下简化数据:
AreaOfInterest
和id
和value
:1, "Car"
,2, "Bike"
,3, "Ship"
AreaOfInterestBeans
和id
和value
:5, "Limo"
,2, "Scooter"
,7, "Yacht"
结果AreaOfInterestBeans
将具有ID 2
的替换值:Scooter
-> Bike
。
AreaOfInterestBeans
和id
和value
:5, "Limo"
,2, "Bike"
,7, "Yacht"
另一种Stream方法:
listOfBeans = listOfBeans.stream()
.peek(aoiBean -> list.stream()
.filter(aoi -> aoi.getId() == aoiBean.getId())
.findFirst()
.ifPresent(i -> aoiBean.setValue(i.getValue())))
.collect(Collectors.toList());