Home > Software engineering >  How to convert Long to BigDecimal while also using a Stream
How to convert Long to BigDecimal while also using a Stream

Time:05-18

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.

CodePudding user response:

It can be achieved 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.

CodePudding user response:

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.

  • Related