'Stream, return value of characters that didn't pass the filter
I would like to count the characters that didn't pass the filter, and return this value too. How can i do that?
My exc:
Within class LambdasStreamExercise, implement method dnaToWeight in order to determine the molecular weight of a DNA sequence string from its nucleotides. Implement these individual steps in your stream:
- Start with
DNA.chars()to initiate a Stream. This will be one of integers. - Filter out those that do not represent regular DNA (Challenge: and count them)
- Convert to a stream of Character objects from the given DNA sequence
- Convert the Characters into Nucleotide objects
- Convert the Nucleotide objects to their weights
- Sum the weights and return the result (And report the number of rejected nucleotides)
public static double dnaToWeight(String DNA) {
double dnaWeightTotal = DNA.chars()
.filter(c -> c == 'A' || c == 'T' || c == 'G' || c == 'C')
.mapToObj(c -> new Nucleotide((char) c))
.mapToDouble(c -> (double) c.getWeight())
.sum();
return dnaWeightTotal;
}
Solution 1:[1]
One clean way to do the job would be to make an intermediate list:
public static double dnaToWeight(String DNA) {
List<Double> weights = DNA.chars()
.filter(c -> c == 'A' || c == 'T' || c == 'G' || c == 'C')
.mapToObj(c -> new Nucleotide((char) c).getWeight())
.toList();
int countNonRegular = DNA.length() - weights.size(); // to be used elsewhere
return weights.stream().reduce(Double::sum).orElse(0.0);
}
Note: The method toList is new in Java 16.
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 |
