Java工具--stream流
- 过滤(filter)
- 统计
- 遍历(map)
- 规约(reduce)
- 排序(sorted)
- 去重(distinct)
- [findAny() 和 findFirst()](#findAny() 和 findFirst())
- 判断(anyMatch,allMatch,noneMatch)
- 分组
- [toList() toSet() toMap()](#toList() toSet() toMap())
过滤(filter)
java
List<Integer> numberList = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
List<String> StringList = Arrays.asList("apple", "orange", "banana", "grape", "apple", "kiwi");
// 筛选出所有的偶数 >>>[2, 4, 6, 8, 10]
List<Integer> evenList = numberList.stream().filter(num -> num%2==0).collect(Collectors.toList());
// 筛选出所有非a开头的字符串 >>>[orange, banana, grape, kiwi]
List<String> strList = StringList.stream().filter(item -> !item.startsWith("a")).collect(Collectors.toList());
统计
求最大最小和均值
使用 mapToInt() 求整数列表中的最大值、最小值、总和、平均值。
java
List<Integer> numberList = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
// 10
int max = numberList.stream().mapToInt(Integer::intValue).max().getAsInt();
// 1
int min = numberList.stream().mapToInt(Integer::intValue).min().getAsInt();
// 55
int min = numberList.stream().mapToInt(Integer::intValue).sum();
// 5.5
double avg = numberList.stream().mapToInt(Integer::intValue).average().getAsDouble();
// 计算双精度列表中所有数字的平均值
List<Double> doubleList = Arrays.asList(1.1, 2.2, 3.3, 4.2, 5.2, 6.1);
// 3.6833333333333336
double average = doubleList.stream().reduce(0.0, (a, b) -> a + b) / doubleList.size();
double average2 = doubleList.stream().mapToDouble(Double::doubleValue).average().getAsDouble();
java
//获取年龄最大的学生
Student ageMaxStudent = list.stream().max(Comparator.companing(Student::getAge)).get();
//获取年龄最小的学生
Student ageMinStudent = list.stream().min(Comparator.companing(Student::getAge)).get();
求和(sum)
java
List<Integer> numberList = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
List<Double> doubleList = Arrays.asList(1.1, 2.2, 3.3, 4.2, 5.2, 6.1);
List<Long> longNumberList = Arrays.asList(10L, 30L, 50L, 60L, 70L, 80L, 90L);
// 55
int m = numberList.stream().mapToInt(Integer::intValue).sum();
// 22.1
double n = doubleList.stream().mapToDouble(Double::doubleValue).sum();
// 390
long w = longNumberList.stream().mapToLong(Long::longValue).sum();
// 55
int sum1 = numberList.stream().reduce(0, (a, b) -> a + b);
int sum2 = numberList.stream().reduce(0, Integer::sum);
过滤后,对数据进行统计
java
// 计算整数列表中所有偶数的和 >>>30
int sum = numberList.stream()
.filter(num -> num%2==0)
.mapToInt(Integer::intValue)
.sum();
// 统计长度大于5的字符串数量 >>>2
long count = StringList.stream()
.filter(str -> str.length()>5)
.count();
// 查找字符串列表中所有字符串的长度的总和 >>>31
int lengthSum = StringList.stream().mapToInt(String::length).reduce(0, Integer::sum);
遍历(map)
java
List<Integer> numberList = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
List<String> StringList = Arrays.asList("apple", "orange", "banana", "grape", "apple", "kiwi");
// 以整数列表作为输入,返回每个元素的平方的新列表 >>>[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
List<Integer> squareList = numberList.stream().map(num -> num*num).collect(Collectors.toList());
// 以字符串列表作为输入,返回每个字符串的长度的新列表 >>>[5, 6, 6, 5, 5, 4]
// map中的方法可以简化成 .map(String::length)
List<Integer> lenList = StringList.stream().map(item -> item.length()).collect(Collectors.toList());
规约(reduce)
java
List<Integer> numberList = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
// 10
int maxNum = numberList.stream().reduce(Integer::max).get();
// 1
int minNum = numberList.stream().reduce(Integer::min).get();
// 55
int sumNum = numberList.stream().reduce(0, Integer::sum);
// 55
int sum = numberList.stream().reduce(0, (a, b) -> a + b);
// 3628800
int product = numberList.stream().reduce(1, (a, b) -> a * b);
java
List<Integer> numberList = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
List<String> StringList = Arrays.asList("apple", "orange", "banana", "grape", "apple", "kiwi");
// 在整数列表中找出最大元素 >>>10
int max = numberList.stream().reduce(0, (a, b) -> a>b? a : b);
// 查找字符串列表中最长的字符串 >>>Optional[banana]
String maxLengthStr = StringList.stream().reduce((s1, s2) -> s1.length() > s2.length()? s1 : s2).toString();
// 查找字符串列表中最短的字符串 >>>Optional[kiwi]
String minLengthStr = StringList.stream().reduce((s1, s2) -> s1.length() < s2.length()? s1 : s2).toString();
将列表中的所有字符串连接成一个字符串
java
// apple@orange@banana@grape@apple@kiwi@
String concat1 = StringList.stream().reduce("", (a, b) -> a + b + "@");
// apple@orange@banana@grape@apple@kiwi
String concat2 = StringList.stream().collect(Collectors.joining("@"));
// apple@orange@banana@grape@apple@kiwi
String concat3 = String.join("@", StringList);
排序(sorted)
java
List<String> StringList = Arrays.asList("apple", "orange", "banana", "grape", "apple", "kiwi");
// 将每个字符串装换为大写,然后按字母顺序排序
// [APPLE, APPLE, BANANA, GRAPE, KIWI, ORANGE]
List<String> sortedUpperCase = StringList.stream()
.map(String::toUpperCase)
.sorted()
.collect(Collectors.toList());
java
List<Integer> numberList = Arrays.asList(12, 2, 33, 24, 5, 61, 27, 8, 39, 10);
// 升序 >>>[2, 5, 8, 10, 12, 24, 27, 33, 39, 61]
List<Integer> sort1NumberList = numberList.stream().sorted().collect(Collectors.toList());
List<Integer> sort2NumberList = numberList.stream().sorted(Comparator.comparing(item->item)).collect(Collectors.toList());
// 降序 >>>[61, 39, 33, 27, 24, 12, 10, 8, 5, 2]
List<Integer> sortReverseNumberList = numberList.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
// 降序 >>>[61, 39, 33, 27, 24, 12, 10, 8, 5, 2]
List<Integer> numberList1 = Arrays.asList(12, 2, 33, 24, 5, 61, 27, 8, 39, 10);
numberList1.sort((objectA, objectB) -> objectB.compareTo(objectA));
// 升序 >>>[2, 5, 8, 10, 12, 24, 27, 33, 39, 61]
List<Integer> numberList2 = Arrays.asList(12, 2, 33, 24, 5, 61, 27, 8, 39, 10);
numberList2.sort((objectA, objectB) -> objectA.compareTo(objectB));
若需要排序的不是简单数字列表,是对象列表
List sortNumberList = numberList.stream().sorted(Comparator.comparing(item->item.getAge())).collect(Collectors.toList());
studentList.sort((objectA, objectB) -> objectB.getAge().compareTo(objectA.getAge()));
去重(distinct)
java
// 去重 >>>[apple, orange, banana, grape, kiwi]
List<String> unique = StringList.stream().distinct().collect(Collectors.toList());
findAny() 和 findFirst()
使用 findAny() 和 findFirst() 获取第一条数据。
java
List<String> stringList = Arrays.asList("apple", "orange", "banana", "grape", "apple", "kiwi");
String str1 = stringList.stream().filter(item -> item.endsWith("e")).findAny().orElse(null);
String str2 = stringList.stream().filter(item -> item.endsWith("e")).findAny().orElse(null);
findFirst() 和 findAny() 都是获取列表中的第一条数据,但是findAny()操作,返回的元素是不确定的,对于同一个列表多次调用findAny()有可能会返回不同的值。使用findAny()是为了更高效的性能。如果是数据较少,串行地情况下,一般会返回第一个结果,如果是并行(parallelStream并行流)的情况,那就不能确保是第一个。
判断(anyMatch,allMatch,noneMatch)
- anyMatch(T -> boolean)
使用 anyMatch(T -> boolean) 判断流中是否有一个元素匹配给定的 T -> boolean 条件。 - allMatch(T -> boolean)
使用 allMatch(T -> boolean) 判断流中是否所有元素都匹配给定的 T -> boolean 条件。 - noneMatch(T -> boolean)
使用 noneMatch(T -> boolean) 流中是否没有元素匹配给定的 T -> boolean 条件。
java
List<String> stringList = Arrays.asList("apple", "orange", "grape", "apple");
List<Integer> numberList = Arrays.asList(12, 2, 33, 24, 5, 61, 27, 8, 39, 10);
// 存在元素以a开头 >>>true
boolean anyStartsWithA = stringList.stream().anyMatch(item -> item.startsWith("a"));
// 所有元素以e结尾 >>>true
boolean allEndsWithB = stringList.stream().allMatch(item -> item.endsWith("e"));
// 没有元素以g开头 >>>false
boolean noneStartsWithG = stringList.stream().noneMatch(item -> item.startsWith("g"));
// 没有元素以k开头 >>>true
boolean noneStartsWithK = stringList.stream().noneMatch(item -> item.startsWith("k"));
// 所有元素都是偶数 >>>false
boolean allEven = numberList.stream().allMatch(item -> item%2==0);
分组
java
@Test
public void test011() {
// User对象的四个属性,(id,areaCode,name,roomNum,peopleNum)
List<User> userList = new ArrayList<>();
userList.add(new User(1L, "210300", "熊大",1, 2));
userList.add(new User(2L, "210300", "赵二",2, 3));
userList.add(new User(3L, "210100", "张三",3, 4));
userList.add(new User(4L, "210100", "李四",4, 5));
userList.add(new User(5L, "210400", "王五",5, 6));
/** 返回一个Map,其中键是areaCode,值是具有该areaCode的用户列表
* {
* 210400=[User(id=5, areaCode=210400, name=王五, roomNum=5, peopleNum=6)],
* 210300=[User(id=1, areaCode=210300, name=熊大, roomNum=1, peopleNum=2), User(id=2, areaCode=210300, name=赵二, roomNum=2, peopleNum=3)],
* 210100=[User(id=3, areaCode=210100, name=张三, roomNum=3, peopleNum=4), User(id=4, areaCode=210100, name=李四, roomNum=4, peopleNum=5)]
* }
*/
Map<String, List<User>> areaCodeAndUserMap = userList
.stream().collect(Collectors.groupingBy(User::getAreaCode));
/** 按areaCode分组,并收集组中roomNum最大的User对象
* {
* 210400=Optional[User(id=5, areaCode=210400, name=王五, roomNum=5, peopleNum=6)],
* 210300=Optional[User(id=2, areaCode=210300, name=赵二, roomNum=2, peopleNum=3)],
* 210100=Optional[User(id=4, areaCode=210100, name=李四, roomNum=4, peopleNum=5)]
* }
*/
Map<String, Optional<User>> areaCodeAndMaxRoomMap = userList.stream()
.collect(Collectors.groupingBy(
User::getAreaCode,
Collectors.maxBy(Comparator.comparingInt(User::getRoomNum))
));
// 按areaCode分组,并将组中的userID收集为List
// {210400=[5], 210300=[1, 2], 210100=[3, 4]}
Map<String, List<Long>> areaCodeAndUserIdMap = userList
.stream().collect(Collectors.groupingBy(
User::getAreaCode,
Collectors.mapping(User::getId, Collectors.toList())
));
// 按areaCode分组,并统计个数
// {210400=1, 210300=2, 210100=2}
Map<String, Long> areaCodeNumMap = userList
.stream().collect(
Collectors.groupingBy(User::getAreaCode, Collectors.counting())
);
// 按areaCode分组,并统计组中的roomNum平均值
// {210400=5.0, 210300=1.5, 210100=3.5}
Map<String, Double> areaCodeAndRoomSumMap = userList
.stream().collect(
Collectors.groupingBy(User::getAreaCode, Collectors.averagingInt(User::getRoomNum))
);
// 按areaCode分组,并统计组中的roomNum和
// {210400=5, 210300=3, 210100=7}
Map<String, Integer> areaCodeAndRoomNumMap = userList
.stream().collect(
Collectors.groupingBy(User::getAreaCode, Collectors.summingInt(User::getRoomNum))
);
// 按areaCode分组,并统计组中的peopleNum和
// {210400=6, 210300=5, 210100=9}
Map<String, Integer> areaCodeAndPeopleNumMap = userList
.stream().collect(
Collectors.groupingBy(User::getAreaCode, Collectors.summingInt(User::getPeopleNum))
);
}
@Data
@NoArgsConstructor
@AllArgsConstructor
class User{
private Long id;
private String areaCode;
private String name;
private Integer roomNum;
private Integer peopleNum;
}
java
List<String> StringList = Arrays.asList("apple", "orange", "banana", "grape", "apple", "kiwi");
// 按字符串长度分组
Map<Integer, List<String>> groups = new HashMap<>();
for (String item : StringList) {
int length = item.length();
if (!groups.containsKey(length)) {
groups.put(length, new ArrayList<>());
}
groups.get(length).add(item);
}
// {4=[kiwi], 5=[apple, grape, apple], 6=[orange, banana]}
System.out.println(groups);
toList() toSet() toMap()
用toMap方法时,必须确保选择的key是唯一且非空的
java
@Test
public void test011() {
// User对象的四个属性,(id,areaCode,name,roomNum,peopleNum)
List<User> userList = new ArrayList<>();
userList.add(new User(1L, "210300", "熊大",1, 2));
userList.add(new User(2L, "210300", "赵二",2, 3));
userList.add(new User(3L, "210100", "张三",3, 4));
userList.add(new User(4L, "210100", "李四",4, 5));
userList.add(new User(5L, "210400", "王五",5, 6));
// [210300, 210300, 210100, 210100, 210400]
List<String> list1 = userList.stream().map(User::getAreaCode).collect(Collectors.toList());
// [210400, 210300, 210100]
Set<String> set1 = userList.stream().map(User::getAreaCode).collect(Collectors.toSet());
/**
* {
* 李四=User(id=4, areaCode=210100, name=李四, roomNum=4, peopleNum=5),
* 张三=User(id=3, areaCode=210100, name=张三, roomNum=3, peopleNum=4),
* 熊大=User(id=1, areaCode=210300, name=熊大, roomNum=1, peopleNum=2),
* 赵二=User(id=2, areaCode=210300, name=赵二, roomNum=2, peopleNum=3),
* 王五=User(id=5, areaCode=210400, name=王五, roomNum=5, peopleNum=6)
* }
*/
Map<String, User> map1 = userList
.stream().collect(Collectors.toMap(User::getName, Function.identity()));
/**
* {
* 1=User(id=1, areaCode=210300, name=熊大, roomNum=1, peopleNum=2),
* 2=User(id=2, areaCode=210300, name=赵二, roomNum=2, peopleNum=3),
* 3=User(id=3, areaCode=210100, name=张三, roomNum=3, peopleNum=4),
* 4=User(id=4, areaCode=210100, name=李四, roomNum=4, peopleNum=5),
* 5=User(id=5, areaCode=210400, name=王五, roomNum=5, peopleNum=6)
* }
*/
Map<Long, User> map2 = userList
.stream().collect(Collectors.toMap(User::getId, Function.identity()));
// {李四=5, 张三=4, 熊大=2, 赵二=3, 王五=6}
Map<String, Integer> map3 = userList
.stream().collect(Collectors.toMap(User::getName, User::getPeopleNum));
// {1=熊大, 2=赵二, 3=张三, 4=李四, 5=王五}
Map<String, String> map4 = userList
.stream().collect(Collectors.toMap(
item -> String.valueOf(item.getId()),
User::getName
));
}