Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”
- Situation: A list of collection objects, now I want to get the ID of each object in this collection, and store these ID values in another collection, so that I can easily query the data. If you were to implement this requirement, how would you implement it?
I’m guessing a lot of people would pick the loop variable, the collection object, take the ID and store it in the collection, and the code looks like this:
List<Clazz> list = clazzes;
List<Long> ids = new ArrayList();
for (Clazz clazz : list) {
ids.add(clazz.getId());
}
Copy the code
But! In fact, this requirement can be solved with a single line of code, with what? For “stream” look at the code:
List<Clazz> list = clazzes;
List<Long> collect = list.stream().map(Clazz::getId).collect(Collectors.toList());
Copy the code
Using a stream of one line of code to solve the key looks clear. The list.stream().map(Clazz::getId).collect(Collectors. ToList ()) line uses two new JAVA8 features
- Double colons Double colons are methods passed as arguments to desired methods, or to stream(). Class name: : method name
- You can also use the Collectors class to convert a stream into a collection element stream. For details, see Searching the Network
I used a lot of streams when I was writing filter criteria and found it really comfortable to use stream streams.
I’ll start by describing my most recent interface: this interface needs to display four pie charts. The four pie charts are as follows: 1. I want to complete this query in one interface. My ideas are as follows:
1. Is to write multiple query statements need a query a (but various filtering conditions down is very troublesome)
2. View can be used for multiple calls (but there will be in operation in the query feel troublesome)
3. Filter each operation by using stream to find out the teacher information that meets the screening conditions
TeacherList (set type) Long count1 = teacherList.stream().filter(e -> equetGender ().equals(0)).count(); Long count2 = teacherList.stream().filter(e -> equetGender ().equals(1)).count(); // The number of girlsCopy the code
And by doing that you can actually figure out the quantity without having to do the math
For more detailed information about stream, you can search online
I’m still learning about stream on the surface and I still have a lot of flexibility to use it.