Java8 中通过 Stream 对列表操作的几种方法

1. Stream 的distinct()方法–去重

因为 String 类已经覆写了 equals()hashCode() 方法,所以可以去重成功。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@Test
public void listDistinctByStreamDistinct() {
// 1. 对于 String 列表去重
List<String> stringList = new ArrayList<String>() {{
add("A");
add("A");
add("B");
add("B");
add("C");
}};
out.print("去重前:");
for (String s : stringList) {
out.print(s);
}
out.println();
stringList = stringList.stream().distinct().collect(Collectors.toList());
out.print("去重后:");
for (String s : stringList) {
out.print(s);
}
out.println();
}

结果如下:

1
2
去重前:AABBC
去重后:ABC

2.groupingBy方法

注:lambda表达式是一行的函数。它们在其他语言中也被称为匿名函数

它接收一个函数作为参数,即可以传lambda进来

1. 简单类型分组
1
2
3
4
5
6
@Test
public void test01() {
List<Integer> intList = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 1, 2, 3);
Map<Integer, List<Integer>> collect = intList.stream().collect(Collectors.groupingBy(e -> e%2));
System.out.println(collect);
}
2. 对象,按一个属性分组

这里用到的User::getEducation,class名字+双冒号+方法名,等同于lambda表达式e -> e.getEduction()

1
2
3
4
5
6
7
8
9
10
11
12
13
@Test
public void test02() {
List<User> userList = Arrays.asList(new User(0, "zhangsan", "zhangsan@qq.com", 20, "High School"),
new User(1, "lisi", "lisi@qq.com", 20, "High School"),
new User(2, "wangwu", "wangwu@qq.com", 20, "High School"),
new User(3, "lilei", "lilei@qq.com", 25, "Graduate"),
new User(4, "hanmeimei", "hanmeimei@qq.com", 26, "Graduate"),
new User(5, "lucy", "lucy@qq.com", 25, "Graduate"));

Map<String, List<User>> collect = userList.stream().collect(Collectors.groupingBy(User::getEducation));

System.out.println(collect);
}
3. 对象,按多个属性分组

嵌套分组 (groupingBy 接收两个参数)

1
2
3
4
Map<Integer, Map<String, List<User>>> collect =
userList.stream().collect(Collectors.groupingBy(User::getAge, Collectors.groupingBy(User::getEducation)));

System.out.println(collect.get(20).get("High School"));

leecode相关题应用

49. 字母异位词分组

给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。

字母异位词 是由重新排列源单词的所有字母得到的一个新单词。

示例 1:

1
2
输入: strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
输出: [["bat"],["nat","tan"],["ate","eat","tea"]]

示例 2:

1
2
输入: strs = [""]
输出: [[""]]

示例 3:

1
2
输入: strs = ["a"]
输出: [["a"]]

提示:

  • 1 <= strs.length <= 104
  • 0 <= strs[i].length <= 100
  • strs[i] 仅包含小写字母

题解:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {

public List<List<String>> groupAnagrams(String[] strs) {

​ List<List<String>> arraylist = new ArrayList<List<String>>(Arrays.stream(strs).collect(Collectors.groupingBy(s -> {

char[] array = s.toCharArray();

​ Arrays.sort(array);

return new String(array);

​ })).values());

return arraylist;

}

}