Search code examples
javalambdajava-streamcollectors

Convert average from lambda stream to Integer


I have a map and would like to have an integer instead of a double but I can't seem to get it to convert. My problem seems to be the 'averagingInt' part. I get the correct value, I just want to round it down. Thank you in advance.

public Map<String,Integer> executeSQL14(){
    return records.stream()
            .filter(p->p.getSource().equals("a") || p.getSource().equals("b"))
            .filter(p->p.getDestination().equals("f") || p.getDestination().equals("h"))
            .filter(p->p.getExtendedSecurityCheck().equals("n"))
            .collect(Collectors.groupingBy(Record::getDestination, Collectors.averagingInt(Record::getWeight)));
}

Solution

  • You possibly could use the alternative toMap as:

    public Map<String,Integer> executeSQL14(List<Record> records) {
        return records.stream()
                .filter(p -> p.getSource().equals("a") || p.getSource().equals("b"))
                .filter(p -> p.getDestination().equals("f") || p.getDestination().equals("h"))
                .filter(p -> p.getExtendedSecurityCheck().equals("n"))
                .collect(Collectors.toMap(Record::getDestination, Record::getWeight, (a, b) -> (a + b) / 2));
    }
    

    or possibly perform an additional finishing operation using collectingAndThen as:

    public Map<String,Integer> executeSQL14(List<Record> records) {
        return records.stream()
                .filter(p -> p.getSource().equals("a") || p.getSource().equals("b"))
                .filter(p -> p.getDestination().equals("f") || p.getDestination().equals("h"))
                .filter(p -> p.getExtendedSecurityCheck().equals("n"))
                .collect(Collectors.groupingBy(Record::getDestination, 
                        Collectors.collectingAndThen(Collectors.averagingInt(Record::getWeight), Double::intValue)));
    }