How to convert Long to BigDecimal while also using a Stream

Viewed 102

I'm struggling to understand how can I make the following code work.

The field count_human_dna of my stat class is of type BigDecimal, with setting the type as Long this works, but I need to change it to BigDecimal, can somehow tell me how could I make this work for BigDecimal field?

stat.setCount_human_dna(dnaSamples.stream()
    .filter(x -> x.getType().equals("Human"))
    .collect(Collectors.counting()));

This code is counting all the dnaSamples which type belong to Human.

2 Answers

Use the BigDecimal#valueOf method for the conversion from long to BigDecimal.

stat.setCount_human_dna(BigDecimal.valueOf(dnaSamples.stream().filter(x -> x.getType().equals("Human")).collect(Collectors.counting())));

See the JavaDocs for more detail.

The most simple and efficient way to do is to use terminal operation count() which returns the number of elements in the stream as long and then convert into BigDecimal:

stat.setCount_human_dna(getDNACount(dnaSamples));
public static BigDecimal getDNACount(Collection<Sample> dnaSamples) {
    long humanSamples = dnaSamples.stream()
        .filter(x -> x.getType().equals("Human"))
        .count();

    return BigDecimal.valueOf(humanSamples);
}

And you can produce the result of type BigDecimal directly from the stream using reduce() a terminal operation:

stat.setCount_human_dna(getDNACount(dnaSamples));
public static BigDecimal getDNACount(Collection<Sample> dnaSamples) {
    return dnaSamples.stream()
        .filter(x -> x.getType().equals("Human"))
        .reduce(BigDecimal.ZERO,
                (total, next) -> total.add(BigDecimal.ONE),
                BigDecimal::add);
}

Sidenote: I'm not an expert in such questions as DNA analysis, but the result of this reduction will always be a whole number. You might consider utilizing BigInteger instead of BigDecimal.

Related