0

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.

Stefan Zobel
  • 3,182
  • 7
  • 28
  • 38
TonyRomero
  • 182
  • 1
  • 4
  • 14

3 Answers3

3

You can easily do it using com.google.guava library (version 21 and above)

public List<Boolean> concatenate(List<Boolean> firstList, List<Boolean> secondList) {
        return Streams.zip(firstList.stream(), secondList.stream(), (a, b) -> (a && b))
                .collect(Collectors.toList());
    }
saw1k
  • 131
  • 1
  • 2
1
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.

Harshal Parekh
  • 5,918
  • 4
  • 21
  • 43
1

The problem with the filtering is that you use indexOf which always return the first occurrence of the element, since you have Booleans.

Given that the size of the two lists are equal, you can go with the classical way:

public List<Boolean> concatenate(List<Boolean> l1, List<Boolean> l2) {
    List<Boolean> result = new ArrayList<>();
    for(int index = 0; index < l1.size(); index ++) {
        result.add(l1.get(index) && l2.get(index));
    }
    return result; 
}
tdavid
  • 95
  • 7