Practical collection: Java8 Stream practical tips record

Recently, I found that this Stream is used a lot, and I have mastered the basic grammar. However, when encountering actual scenarios, it takes a lot of time to write them out. Therefore, we summarize the writing methods of common scenarios to facilitate rapid application in real scenarios.

In addition, for basic grammar and errors encountered, you can refer to my other articles

  • Basic syntax reference

New features of Java8: Detailed explanation of new features such as HashMap optimization, lambda, and Stream

  • Problems encountered and solutions

这个文章访问量是真多,应该这个错比较常见,大家通过搜索引擎搜到了它 Java8-Stream: no instance(s) of type variable(s) R exist so that void conforms to R

1. Scenario overview

1.1, the role of Stream

We use Stream mainly to replace the bloated for loop and perform various sao operations on the collection

1.2. Usage scenarios

There are mainly the following scenarios:

1. group by

2. order by (sorting) 3. where (filtering) 4. distinct (removing duplicates) 5. appLy (performing various operations according to an attribute) 6. extracting an attribute as a list

2. Tips

2.1、group by

Group by gender

userList.stream()
	.collect(Collectors.groupingBy(User::getSex));
复制代码

2.2、order by

Sort by user age (ascending/descending) and take top3

userList.stream()
	.sorted(Comparator.comparing(User::getAge).reversed())
	.limit(3)
	.collect(Collectors.toList());
复制代码

2.3、where

2.3.1, the most value filter

Get the object with the max/min of a property

// 最小
Optional<User> min = userList.stream()
	.min(Comparator.comparing(User::getAge));
// 最大
Optional<User> max = userList.stream()
	.max(Comparator.comparing(User::getAge));

// 获得对象
User user = min.get();
复制代码

2.3.2. Conditional filtering

Filter users under the age of 30

userList.stream()
	.filter(e -> e.getAge() < 30)
	.collect(Collectors.toList());
复制代码

Select user age > 20 and gender is male (sex=1)


userList.stream()
	.filter(u -> u.getAge() > 20 && u.getSex() == 1)
	.collect(Collectors.toList());
复制代码

Query the first user named "Li Hua"

userList.stream().
	filter(u -> u.getName().equals("小明"))
	.findFirst().orElse(ll);
复制代码

2.4、distinct

Get all usernames and deduplicate

userList.stream()
	.map(User::getName)
	.distinct()
	.collect(Collectors.toList());
复制代码

Deduplication according to a field

memberListAll.stream()
	.collect(Collectors.collectingAndThen(
                        Collectors.toCollection(
				() -> new TreeSet<>(Comparator.comparing(WorkWxUserInfoVO :: getUserid))), ArrayList::new)
	);
复制代码

2.5、apply

Mass assignment to a property

userList.forEach(e -> {
            e.setName("hello");
        });
复制代码

process a field

userList.stream()
	.map(user -> {user.setName(user.getName().replaceAll("\u0000", "")); return user;})
	.collect(Collectors.toList());
复制代码

Get an object based on a field

List<User> userList = userIds.stream()
            .map(id -> {
                User user = userService.getUserById(id);
                return user;
            })
            .collect(Collectors.toList());
复制代码

2.6, extract attributes

Extract a single attribute: get all usernames and deduplicate

userList.stream()
	.map(User::getName)
	.distinct()
	.collect(Collectors.toList());
复制代码

Extract multiple attributes: combine menuId and menuName into map (menuId is unique)

userList.stream()
	.collect(Collectors.toMap(User::getMenuId, User::getMenuName)));
复制代码

Extract multiple attributes: combine menuId and menuName into map (menuId is not unique)

userList
	//去重
	.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(
                                () -> new TreeSet<>(Comparator.comparing(User :: getMenuId))), ArrayList::new))
	//转map
	.stream().collect(Collectors.toMap(User::getMenuId, User::getMenuName)));
复制代码



The above only records the most common scenarios. For more scenarios, please refer to: Java8 New Features: Detailed explanation of new features such as HashMap optimization, lambda, and Stream

Guess you like

Origin juejin.im/post/7088512333042958350
Recommended