Convert average from lambda stream to Integer

Rachel Colins :

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)));
}
Naman :

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)));
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=101447&siteId=1