Java 8 stream 流获取 list 中最大值、最小值、总和值、平均值
模拟普通对象输出:
// list
static List<Employee> empList = new ArrayList<Employee>();
private static void initEmp(){
empList.add(new Employee("张三",30));
empList.add(new Employee("张三1",96));
empList.add(new Employee("张三2",23));
empList.add(new Employee("张三3",69));
empList.add(new Employee("张三4",85));
empList.add(new Employee("张三5",62));
empList.add(new Employee("张三6",12));
empList.add(new Employee("张三7",99));
empList.add(new Employee("张三8",11));
}
//获取员工年龄的最大、最小、总和、平均值
public static void main(String[] args) {
initEmp();
int sum = empList.stream().mapToInt(Employee->Employee.getAge()).sum();
int max = empList.stream().mapToInt(Employee->Employee.getAge()).max().getAsInt();
int min = empList.stream().mapToInt(Employee->Employee.getAge()).min().getAsInt();
double avg = empList.stream().mapToInt(Employee->Employee.getAge()).average().getAsDouble();
System.out.println("最大值:"+max+"\n最小值:"+min+"\n总和:"+sum+"\n平均值:"+avg);
模拟SQL输出:
import org.testng.collections.Lists;
import org.testng.collections.Maps;
import java.util.List;
import java.util.Map;
/** * @Class: TestStream * @Description: * @Author: Jerry(姜源) * @Create: 2020/9/25 16:14 */
public class TestStream {
public static void main(String[] args) {
List<Map> list = initData();
// 取SQL中 number列 的最大值
int max = list.stream().mapToInt(
m -> m.get("number") != null ? Integer.parseInt(m.get("number").toString()) : 0
).max().getAsInt();
System.err.println("max = " + max); //22
// 取SQL中 number列 的最小值
int min = list.stream().mapToInt(
m -> m.get("number") != null ? Integer.parseInt(m.get("number").toString()) : 0
).min().getAsInt();
System.err.println("min = " + min); //1
// 取SQL中 number列 的总和值
int sum = list.stream().mapToInt(
m -> m.get("number") != null ? Integer.parseInt(m.get("number").toString()) : 0
).sum();
System.err.println("sum = " + sum); //26
// 取SQL中 number列 的平均值
double avg = list.stream().mapToInt(
m -> m.get("number") != null ? Integer.parseInt(m.get("number").toString()) : 0
).average().getAsDouble();
System.err.println("avg = " + avg); //8.666666666666666
}
/** * 模拟 SQL 的输出 * test number * A 1 * B 22 * C 3 */
public static List<Map> initData() {
List<Map> list = Lists.newLinkedList();
Map map = Maps.newLinkedHashMap();
map.put("test", "A");
map.put("number", 1);
list.add(map);
Map map1 = Maps.newLinkedHashMap();
map1.put("test", "B");
map1.put("number", 22);
list.add(map1);
Map map2 = Maps.newLinkedHashMap();
map2.put("test", "C");
map2.put("number", 3);
list.add(map2);
System.err.println("sql result = " + list);
return list;
}
}
还没有评论,来说两句吧...