有两个集合,我要分别操作然后获取其中的相同的属性然后写逻辑,在1.8之前 可以写成
for (api a : apiList) {
for (app b : appList) {
if (a.getPid().equals(b.getPid())) {
a.setPidName(b.getPidName());
}
}
}
想请教下,如果用stream怎么写呢 这个逻辑?
把第二个list转成map,pid为key,pidName为value,遍历第一个list,setpidName(map.get(pid))
public static void main(String[] args) {
List<String> list1 =
new ArrayList<String>() {
{
add("1");
add("2");
}
};
List<String> list2 =
new ArrayList<String>() {
{
add("2");
}
};
list1.stream()
.filter(s1 -> list2.stream().anyMatch(s2 -> s1.equals(s2)))
.forEach(
s -> {
// todo
System.out.println(s);
});
}
public void test() {
List<App> appList = new ArrayList<>();
List<App> appList2 = new ArrayList<>();
Map<String, App> maps = appList2.stream().collect(Collectors.toMap(App::getId, s -> s, (k1, k2) -> k1));
appList.forEach(a -> {
App b = maps.get(a.getId());
if (Objects.nonNull(b)) {
a.setName(b.getName());
}
});
}
是写成linq吗?
c#中的语法可以是
from a in apiList
join b in appList
on a.Pid equals b.Pid
select new {
...
}
public static void main(String[] args) {
List<String> list1 = new ArrayList<>();
List<String> list2 = new ArrayList<>();
list1.stream().forEach(p1->{
list2.stream().forEach(p2->{
if(p1.equals(p2)){
//todo
}
});
});
}