Java 8, stream with another List Index based on

QA_Col :

I have this code

List<Integer> numbers = new ArrayList<>(30, 25, 17, 12 ,8, 5, 3, 2));
List<Integer> indices = new ArrayList<>(5, 3, 2));
Integer newNumber = 1;
for (int i = indices.size() - 1; i >= 0; i--) {
  newNumber *= (numbers.get(indices.get(i)));
}

newNumber will be: 5*12*17 = 1020

It is possible to do using stream reduce?

Later I need to remove the indices from the original numbers (I was thinking in filter, but the target is the index not Integer object).

List<Integer> newNumbers = new ArrayList<>(numbers);
for (int i = indices.size() - 1; i >= 0; i--) {
  newNumbers.remove(indices.get(i).intValue()); // Remove position
}

Alternatively, I was thinking in this code.

List<Integer> newNumbers2 = new ArrayList<>();
for (int i = 0; i < numbers.size(); i++) {
  if (!indices.contains(i)) {
    newNumbers2.add(numbers.get(i));
  }
}

Is it possible to do it using stream?

Thanks.

Ravindra Ranwala :

Yes you can do it using simple reduction. The identity element of the the reduction is 1 in this case.

int product = indices.stream().mapToInt(numbers::get).reduce(1, (n1, n2) -> n1 * n2);

The answer for the latter question would be,

Set<Integer> indicesSet = new HashSet<>(indices);
List<Integer> newNumbers = IntStream.range(0, numbers.size())
    .filter(n -> !indicesSet.contains(n))
    .mapToObj(n -> numbers.get(n))
    .collect(Collectors.toList());

In mathematics, an identity element is a special type of element of a set with respect to a binary operation on that set, which leaves any element of the set unchanged when combined with it.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=81065&siteId=1