Are you still traversing the search collection? Stop kidding! Java 8 one line of code is really elegant!

Posted by mithras on Wed, 03 Nov 2021 07:52:32 +0100

background

Yes, if you want to search the List collection, you can use your own contains/ indexOf method to find elements before Java 8, but only complete elements, not fuzzy search or user-defined search. At this time, you can only traverse.

But now it's 2021. Are you still searching for List collection elements in the traditional way of traversing the collection?

Then you're too out. Using stream search elements in Java 8 can be done in one line of code, and it's really elegant! This article will not introduce Stream foundation, Stream series I have written a topic before, I do not understand the official account Java technology stack, and then read in the official account Java tutorial menu.

Stream search

In Java 8, you can convert a List set into a stream. Stream provides a series of powerful search functions, such as filter, find *, * Match and other methods. One line of code can handle the search.

For example, there are initial data:

public static List<User> list = new ArrayList<>();

/**
 * @author: Stack length
 * @from: Official account Java technology stack
 */
@BeforeEach
public void initList() {
    list.add(new User("official account Java Technology stack-Petty", 22, 1));
    list.add(new User("official account Java Technology stack-Tom", 38, 1));
    list.add(new User("official account Java Technology stack-Jessica", 43, 0));
    list.add(new User("official account Java Technology stack-John", 15, 1));
    list.add(new User("official account Java Technology stack-Lily", 25, 0));
    list.add(new User("official account Java Technology stack-Lambs", 28, 0));
    list.add(new User("official account Java Technology stack-Jack", 45, 1));
    list.add(new User("official account Java Technology stack-Addy", 9, 0));
    list.add(new User("official account Java Technology stack-Bob", 61, 1));
    list.add(new User("official account Java Technology stack-Candy", 26, 0));
}

The user information is: name, age and gender.

filter

Use the filter method to realize user-defined search, such as searching for all people whose names contain c in the list \ < user \ > collection:

/**
 * Collection filtering
 * @author: Stack length
 * @from: Official account Java technology stack
 */
@Test
public void filter() {
    System.out.println("Search all names with c People");
    list.stream().filter(u -> u.getName().contains("c")).forEach(System.out::println);
}

Output results:

findFirst (find first)

Find the first element in the Stream, such as the first person with more than 30 years of age in the list \ < user \ > collection:

/**
 * Set search first
 * @author: Stack length
 * @from: Official account Java technology stack
 */
@Test
public void findFirst() {
    System.out.println("Search for the first person over 30 years old");
    User user = list.stream().filter(u -> u.getAge() > 30).findFirst().get();
    System.out.println(user);
}

Output results:

The example is that you need to filter before findFirst, but if you don't want conditions, filter is not necessary.

Stream can not focus on the official account Java technology stack, and then read the Java series tutorial in the official account Java tutorial menu.

findAny (find any)

Find any element in the Stream, such as any person over 30 years old in the list \ < user \ > collection:

/**
 * Set search any one
 * @author: Stack length
 * @from: Official account Java technology stack
 */
@Test
public void findAny() {
    System.out.println("Search for anyone over 30 years old");
    User user = list.stream().filter(u -> u.getAge() > 30).findAny().get();
    System.out.println(user.getName());
}

Output results:

Why is the result the same as findFirst? What's the difference between and findFirst?

findAny is to find any element. If there is less data in the serial stream, the first element will generally be returned, but the result returned in the parallel stream is uncertain. It may be any element in the stream.

The purpose of findAny is to improve the performance of parallel stream operations, but if you need a fixed result, it is recommended to use findFirst.

All the complete sample source code of this article has been uploaded:

https://github.com/javastacks...

anyMatch

Find out whether there are any matches in the elements in the Stream, such as whether there are XX people in the list \ < user \ > collection:

/**
 * The collection matches any element
 * @author: Stack length
 * @from: Official account Java technology stack
 */
@Test
public void anyMatch() {
    System.out.println("Does it exist Jack: " + list.stream().anyMatch(u -> u.getName().contains("Jack")));
    System.out.println("Does it exist Jet: " + list.stream().anyMatch(u -> u.getName().contains("Jet")));
}

Output results:

*The result returned by Match is of type boolean.

noneMatch (null match)

Find out whether there is no match for the elements in the Stream. For example, search whether there are XX people in the list \ < user \ > collection:

/**
 * The collection does not match any element
 * @author: Stack length
 * @from: Official account Java technology stack
 */
@Test
public void noneMatch() {
    System.out.println("Does it not exist Jack: " + list.stream().noneMatch(u -> u.getName().contains("Jack")));
    System.out.println("Does it not exist Jet: " + list.stream().noneMatch(u -> u.getName().contains("Jack")));
}

Output results:

This method is the opposite of anyMatch.

allMatch

Find out whether all elements in the Stream match. For example, search whether everyone in the list \ < user \ > collection is older than XX:

/**
 * Set matches all elements
 * @author: Stack length
 * @from: Official account Java technology stack
 */
@Test
public void allMatch() {
    System.out.println("All are older than 3:" + list.stream().allMatch(u -> u.getAge() > 2));
    System.out.println("All are older than 30:" + list.stream().allMatch(u -> u.getAge() > 30));
}

Output results:

summary

All the above search operations can be done in one line of code. Is it very simple and elegant?

Collections other than List can be converted to List, then converted to Stream, and then searched. For Stream, search is pediatrics. Have you learned to waste it?

Send it to your colleagues quickly to make your code more elegant!

If you add new knowledge points to Java 8 (Lambda, Stream, functional interfaces, etc.), you can't use the official account: Java technology stack, reading in the Java tutorial menu, and I have written a bunch of Java 8+ series tutorials.

All the complete sample source code of this article has been uploaded:

https://github.com/javastacks...

Welcome to Star. The following Java examples will be provided here!

Well, today's sharing is here. The stack will share more interesting Java technology and latest technology information. We will pay attention to the Java push for the official account. I will also organize the main Java interview questions and reference answers. I will reply to the key words in the official account.

Finally, I feel that if my article is useful to you, use your small hand to read and forward it. It is not easy to be original. The stack leader needs your encouragement.

Copyright notice: This article is the public number "Java technology stack" original, original is not easy, reprint, quote the content of this article please indicate the source, all the plagiarism official account + complaint, and retain the right to pursue its legal responsibility.

Recent hot article recommendations:

1.1000 + Java interview questions and answers (2021 latest version)

2.Stop playing if/ else on the full screen. Try the strategy mode. It's really fragrant!!

3.what the fuck! What is the new syntax of xx ≠ null in Java?

4.Spring Boot 2.5 heavy release, dark mode is too explosive!

5.Java development manual (Songshan version) is the latest release. Download it quickly!

Feel good, don't forget to like + forward!

Topics: Java