Java 8 使用 Lambda 表达式操作集合
遍历集合
List<String> list = Stream.of("小明", "小花", "小李").collect(toList());
for (String name : list) {
System.out.println(name);
}
list.forEach(name -> System.out.println(name));
list.forEach(System.out::println);
Map<Integer, String> map = new HashMap<Integer, String>(3) {
{
put(1, "小明");
put(2, "小花");
put(3, "小李");
}
};
for (Integer key : map.keySet()) {
System.out.println(key + " = > " + map.get(key));
}
map.forEach((k, v) -> System.out.println(k + " = > " + v));
一行代码求集合最大值、最小值、总和和平均值
List<Integer> primes = Stream.of(2, 3, 5, 7, 11, 13, 17, 19, 23, 29).collect(toList());
IntSummaryStatistics stats = primes.stream().mapToInt((x) -> x).summaryStatistics();
System.out.println("最大值 " + stats.getMax());
System.out.println("最小值 " + stats.getMin());
System.out.println("总 和 " + stats.getSum());
System.out.println("平均值: " + stats.getAverage());
集合排序
List<Integer> array = Stream.of(3, 2, 4, 6).collect(toList());
array.sort(Integer::compareTo);
@Data
public class User implements Serializable {
private String name;
private Integer age;
private Integer salary;
}
List<User> userList = Stream.of(
new User("小明", 25, 100),
new User("小花", 22, 80),
new User("小李", 22, 79))
.collect(Collectors.toList());
userList.sort(Comparator.comparing(User::getAge));
userList.sort(Comparator.comparing(User::getAge).thenComparing(User::getSalary));
集合分组
Map<Integer, List<User>> map = userList.stream().collect(Collectors.groupingBy(User::getAge));
22 = > [User{name='小花', age=22, salary=80}, User{name='小李', age=22, salary=79}]
25 = > [User{name='小明', age=25, salary=100}]
集合过滤
userList.stream().filter(u -> u.getAge() != 22).collect(toList());
userList.stream().filter(u -> !u.getName().startsWith("王")).collect(toList());
userList.stream().filter(u -> u.getSalary() >= 100).collect(toList());
userList.stream().filter(u -> u.getSalary() <= 200 && !u.getName().startsWith("王")).collect(toList());
其他操作
userList.stream().anyMatch(u -> "小明".equals(u.getName()));
userList.stream().noneMatch(u -> "小兰".equals(u.getName()));
欢迎关注微信公众号"程序员小辉"
![微信图片20190813101011.jpg](https://i-blog.csdnimg.cn/blog_migrate/7f3d1b4822050a18d4e44ed0f17b846d.png)