• 如果您觉得本站非常有看点，那么赶紧使用Ctrl+D 收藏吧

# 使用Java Stream，提取集合中的某一列/按条件过滤集合/求和/最大值/最小值/平均值

2周前 (09-16) 17次浏览

1. java.lang.NullPointerException
2. java.util.NoSuchElementException

1. 提取集合中的某一列（普通提取、去重）
2. 按条件过滤集合
3. 求和
4. 最大值/最小值/平均值

## 1. 数据准备

``````package com.zwwhnly.springbootaction.model;

import lombok.Data;

import java.math.BigDecimal;

@Data
public class Friend {
/**
* 姓名
*/
private String name;

/**
* 年龄
*/
private Integer age;

/**
* 身高
*/
private Long height;

/**
* 所在城市
*/
private String city;

/**
* 体重
*/
private BigDecimal weight;

public Friend(String name, Integer age, Long height, String city, BigDecimal weight) {
this.name = name;
this.age = age;
this.height = height;
this.city = city;
this.weight = weight;
}
}
``````

``````public static List<Friend> getFriendList() {
List<Friend> friendList = new ArrayList<>();
friendList.add(new Friend("小周", 28, 175L, "郑州", new BigDecimal("101.5")));
friendList.add(new Friend("小吴", 28, 170L, "洛阳", new BigDecimal("111.5")));
friendList.add(new Friend("小郑", 29, 176L, "郑州", new BigDecimal("121.5")));
friendList.add(new Friend("小王", 29, 180L, "北京", new BigDecimal("130")));
friendList.add(new Friend("小赵", 27, 178L, "苏州", new BigDecimal("140")));
friendList.add(new Friend("小钱", null, null, "杭州", new BigDecimal("150")));

return friendList;
}
``````

## 2. 提取集合中的某一列

### 2.1 普通提取

``````List<Friend> friendList = getFriendList();
List<String> nameList = friendList.stream().map(Friend::getName).collect(Collectors.toList());

nameList.forEach(name -> System.out.println(name));
``````

### 2.2 提取后去重

``````List<Friend> friendList = getFriendList();
List<Integer> ageList = friendList.stream().map(Friend::getAge).distinct().collect(Collectors.toList());

ageList.forEach(age -> System.out.println(age));
``````

28

29

27

## 3. 按条件过滤集合

``````List<Friend> friendList = getFriendList();

List<Friend> youngPeople = friendList.stream()
.filter(friend -> friend.getAge() != null && friend.getAge() < 29 &&
friend.getHeight() != null && friend.getHeight() > 170L)
.collect(Collectors.toList());
System.out.println(youngPeople);
``````

Friend(name=小周, age=28, height=175, city=郑州, weight=101.5)

Friend(name=小赵, age=27, height=178, city=苏州, weight=140)

## 4. 求和

### 4.1 Integer,Long,Double

``````List<Friend> friendList = getFriendList();

int ageSum = friendList.stream().filter(friend -> friend.getAge() != null).mapToInt(Friend::getAge).sum();
System.out.println(ageSum);
``````

141

``````friendList.add(new Friend("小钱",null,178,"杭州"));
``````

``````List<Friend> friendList = getFriendList();

int ageSum = friendList.stream().mapToInt(Friend::getAge).sum();
System.out.println(ageSum);
``````

### 4.2 BigDecimal

``````List<Friend> friendList = getFriendList();

BigDecimal weightSum = friendList.stream()
.filter(friend -> friend.getWeight() != null)
.map(Friend::getWeight)
System.out.println(weightSum);
``````

754.5

## 5. 最大值/最小值/平均值

### 5.1 Integer,Long,Double

``````List<Friend> friendList = getFriendList();

long heightMax = friendList.stream()
.filter(friend -> friend.getHeight() != null)
.mapToLong(Friend::getHeight)
.max().orElse(0);
System.out.println(heightMax);
``````

180

``````long heightMax = friendList.stream()
.filter(friend -> friend.getHeight() != null)
.mapToLong(Friend::getHeight)
.max().getAsLong();
``````

orElse()源码如下所示：

``````public long orElse(long other) {
return isPresent ? value : other;
}
``````

getAsLong()源码如下所示：

``````public long getAsLong() {
if (!isPresent) {
throw new NoSuchElementException("No value present");
}
return value;
}
``````

``````List<Friend> friendList = getFriendList();

long heightMin = friendList.stream()
.filter(friend -> friend.getHeight() != null)
.mapToLong(Friend::getHeight)
.min().orElse(0);
System.out.println(heightMin);
``````

``````List<Friend> friendList = getFriendList();

double heightAverage = friendList.stream()
.filter(friend -> friend.getHeight() != null)
.mapToLong(Friend::getHeight)
.average().orElse(0D);
System.out.println(heightAverage);
``````

### 5.2 BigDecimal

``````List<Friend> friendList = getFriendList();

BigDecimal weightMax = friendList.stream()
.filter(friend -> friend.getWeight() != null)
.map(Friend::getWeight)
.max(BigDecimal::compareTo)
.orElse(BigDecimal.ZERO);
System.out.println(weightMax);
``````

150

1)为避免出现`java.lang.NullPointerException`异常，注意过滤体重为null的数据

2)因为max()方法的返回值为`Optional`类型，所以我们需要继续调用orElse()方法设置个默认值，这里不要直接使用get()方法，因为当集合为空时，会抛出你肯定遇到过的`java.util.NoSuchElementException`异常：

``````BigDecimal weightMax = friendList.stream()
.filter(friend -> friend.getWeight() != null)
.map(Friend::getWeight)
.max(BigDecimal::compareTo)
.get();
``````

get()方法源码如下所示：

``````public T get() {
if (value == null) {
throw new NoSuchElementException("No value present");
}
return value;
}
``````

``````List<Friend> friendList = getFriendList();

BigDecimal weightMax = friendList.stream()
.filter(friend -> friend.getWeight() != null)
.map(Friend::getWeight)
.min(BigDecimal::compareTo)
.orElse(BigDecimal.ZERO);
System.out.println(weightMax);
``````