I have two lists of Boolean and I need to concatenate them by applying an AND operation to the elements with the same index, I'm expecting to get a list of Booleans that contains the result of doing the operation in pairs.
public List<Boolean> concatenate(List<Boolean> l1, List<Boolean> l2) {
return l1.stream()
.flatMap(e1 -> l2.stream()
.filter(e2-> l1.indexOf(e1) == l2.indexOf(e2))
.map(e2-> e1&&e2))
.collect(Collectors.toList());
}
The size of the resulting list will be l1.size()*l2.size()
so the filter inside the second stream is filtering anything.
List<Boolean> l1 = new ArrayList<>(Arrays.asList(true, false, true));
List<Boolean> l2 = new ArrayList<>(Arrays.asList(false, true, true));
List<Boolean> l3 = IntStream.range(0, min(l1.size(), l2.size()))
.mapToObj(i -> l1.get(i)&&l2.get(i))
.collect(Collectors.toList());
// [false, false, true]
You can use IntStream.range()
to iterate over both the lists at once and .mapToObj()
to convert the &&
to Boolean
and .collect()
to store it in a new List
.
You can simplify the range to .range(0, l1.size())
if you know for sure that both of them are of the same size.