如何为程序转换流API中的嵌套for循环
how to convert nested for loop in stream API for the program
List<Emp> list = Arrays.asList(
new Emp(123, "ABC"), new Emp(123, "BCD"), new Emp(1243, "AUBC"),
new Emp(1233, "ABEC"), new Emp(1233, "ABLC")
);
List<Emp> listNew = new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
for (Emp emp : list) {
if (list.get(i).getCommitId() == emp.getCommitId() && (!list.get(i).getHost().equals(emp.getHost()))) {
Emp emp1 = new Emp();
emp1.setCommitId(list.get(i).getCommitId());
emp1.setHost(list.get(i).getHost());
listNew.add(emp1);
}
}
}
我只需要比较两个 commitid,如果它们相同并且 host 不同,那么 return 这些数据以 emp 列表的形式出现。
您可以创建一个谓词来过滤具有相同提交 ID 和不同主机的 Emp
,过滤流并收集到新列表
public static void main(String[] args) {
List<Emp> list = Arrays.asList(new Emp(123, "ABC"), new Emp(123, "BCD"),
new Emp(1243, "AUBC"), new Emp(1233, "ABEC"), new Emp(1233, "ABLC"));
Predicate<Emp> sameCommitIdWithDifferentHost = (Emp emp) -> list.stream()
.anyMatch(l -> l.getCommitId() == emp.getCommitId() &&
(!l.getHost().equals(emp.getHost())));
List<Emp> listNew = list.stream().filter(sameCommitIdWithDifferentHost).collect(Collectors.toList());
}
List<Emp> list = Arrays.asList(
new Emp(123, "ABC"), new Emp(123, "BCD"), new Emp(1243, "AUBC"),
new Emp(1233, "ABEC"), new Emp(1233, "ABLC")
);
List<Emp> listNew = new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
for (Emp emp : list) {
if (list.get(i).getCommitId() == emp.getCommitId() && (!list.get(i).getHost().equals(emp.getHost()))) {
Emp emp1 = new Emp();
emp1.setCommitId(list.get(i).getCommitId());
emp1.setHost(list.get(i).getHost());
listNew.add(emp1);
}
}
}
我只需要比较两个 commitid,如果它们相同并且 host 不同,那么 return 这些数据以 emp 列表的形式出现。
您可以创建一个谓词来过滤具有相同提交 ID 和不同主机的 Emp
,过滤流并收集到新列表
public static void main(String[] args) {
List<Emp> list = Arrays.asList(new Emp(123, "ABC"), new Emp(123, "BCD"),
new Emp(1243, "AUBC"), new Emp(1233, "ABEC"), new Emp(1233, "ABLC"));
Predicate<Emp> sameCommitIdWithDifferentHost = (Emp emp) -> list.stream()
.anyMatch(l -> l.getCommitId() == emp.getCommitId() &&
(!l.getHost().equals(emp.getHost())));
List<Emp> listNew = list.stream().filter(sameCommitIdWithDifferentHost).collect(Collectors.toList());
}