'how to convert nested for loop in stream API for the program [closed]
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);
}
}
}
I just need to compare two commitid if both are same and host will be different then return those data in the form of list of emp.
Solution 1:[1]
You can create a predicate to filter the Emp
with the same commit id and a different host, filter the stream and collect to a new list
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());
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | HariHaravelan |