Java | are you still traversing the search collection? Don't be funny. Java 8 one line code solution is really elegant

Keywords: Python Java SQL

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   List set is converted into 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 implement custom search, such as searching in the list < user > collection   All persons whose names contain c:

/**
 * 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 in the search list < user > collection   The first person over 30 years old:

/**
 * Set search first
 * @author: Stack length
 * @from: Official account Java technology stack
 */
@Test
public void findFirst() {
    System.out.println("Search for the first year 30 People");
    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.

findAny (find any)

Find any element in the Stream, such as in the search list < user > collection   Any person over 30 years of age:

/**
 * Set search any one
 * @author: Stack length
 * @from: Official account Java technology stack
 */
@Test
public void findAny() {
    System.out.println("Search for any year greater than 30 People");
    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.

anyMatch

Find out whether there is any match in the elements in the Stream, such as searching in the list < user > collection   Whether there are XX persons:

/**
 * 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, such as searching in the list < user > collection   Whether there are no XX persons:

/**
 * 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 the elements in the Stream match, such as searching in the list < user > collection   Is everyone 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!

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

https://github.com/javastacks/javastack

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

Posted by itsgood on Thu, 25 Nov 2021 20:57:55 -0800