2

I am newly learning lambda expression. I am trying to calculate values.

Here is example:

double sendersCount = 0.0;
double reciversCount = 0.0;
for(RecordDTO record : records){
   if("1".equals(record.getSendersId())) {
     sendersCount += record.getCount().doubleValue();
   } else {
     reciversCount +=  record.getCount().doubleValue();
   }
}

class Record{

private String id;
private BigDecimal count;
private String senderId;

//setters
//getters
}

How we can achieve using Streams and maps?

4
  • sendersCount isn't int. It's a double. Commented Jun 12, 2020 at 12:14
  • records is list Commented Jun 12, 2020 at 12:16
  • 2
    IMHO your current approach would be better than any stream approach. you're better off sticking with the current approach. Commented Jun 12, 2020 at 12:20
  • 1
    Record is a bad name for a class. It's used in Java 14 by java.lang.Record. Commented Jun 12, 2020 at 15:59

1 Answer 1

6

In one way, you can possibly partition the list and then sum the appropriate attribute as -

Map<Boolean, List<Record>> partitioned = records.stream()
        .collect(Collectors.partitioningBy(rec -> rec.getSendersId().equals("1")));

double sendersCount = partitioned.get(Boolean.TRUE).stream()
        .mapToDouble(Record::getSendersCount).sum();
double receiversCount = partitioned.get(Boolean.FALSE).stream()
        .mapToDouble(Record::getReceiversCount).sum();

or as Ousmane has pointed out, you can use downstream summingDouble with a condition to map such as:

Map<Boolean, Double> summingValue = records.stream()
        .collect(Collectors.partitioningBy(r -> "1".equals(r.getSendersId()),
                Collectors.summingDouble(r -> "1".equals(r.getSendersId()) ?
                        r.getSendersCount() : r.getReceiversCount())));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.