简体   繁体   中英

Remove Abnormal values from ArrayList

I got an Arraylist with some inconsistant values, what I'm trying to achieve is getting the average value of the list without counting in the abnormally high or low values.

IE

Values: 20,25,22,24,18,135,25,17,19,1000

The result I would like to achieve is the average value of 20,25,22,24,18,25,17,19. The List can also start with an "Abnormal" value.

How can i use Java to get the desired value?

I assume you know the thresholds for what's normal and abnormal for your case. I'll assume that values between 6 and 999 are "normal", while everything else is abnormal.

Using Java streams:

ArrayList<Integer> values = ...
double average = values.stream().mapToInt(i -> i).filter(i -> i < 1000).filter(i -> i > 5)
            .average().getAsDouble();

Using a for loop:

ArrayList<Integer> values = null;

long sum = 0;
int count = 0;
for (Integer i : values) {
    if (i > 5 && i < 1000) {
        sum += i;
        count++;
    }
}
double average = (double) sum / count;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM