Java8 Stream Lambda

2/22/2017来源:ASP.NET技巧人气:1844

1、Stream的聚合操作

例子:对集合对象进行排序、取值操作(使用2种实现方式)

User liLei = new User(1, "liLei", 28, (short)0);
User hanMeiMei = new User(2, "hanMeiMei", 25, (short)1);
User zhou = new User(3, "zhou", 30, (short)1);
User wu = new User(4, "wu", 32, (short)1);
User zheng = new User(5, "zheng", 29, (short)0);

List<User> users = new ArrayList<>();
users.add(liLei);
users.add(hanMeiMei);
users.add(zhou);
users.add(wu);

// 按年龄从小到大输出年龄大于20的男性用户姓名
// 实现方式一:
List<User> userList = new ArrayList<>();
for (User user: users) {
    if (user.getAge() > 20 && user.getSex() == 1) {
        userList.add(user);
    }
}
Collections.sort(userList, new Comparator<User>() {
    @Override
    public int compare(User o1, User o2) {
        return o1.getAge().compareTo(o2.getAge());
    }
});
List<String> names = new ArrayList<>();
for (User user: userList) {
    names.add(user.getName());
}
System.out.PRintln(names);

// 实现方式二:
List<String> nameList = users.stream()
        .filter(user -> user.getAge() > 20 && user.getSex() == 1)
        .sorted(Comparator.comparing(User::getAge).reversed())
        .map(User::getName)
        .collect(Collectors.toList());
System.out.println(names);

 

结果输出:

[hanMeiMei, zhou, wu]

[hanMeiMei, zhou, wu]

第二种实现方式相比第一种实现方式,更方便高效。

java8的Stream借助Lambda表达式提高了编程速度和程序易读性。