EN
Java 8 - find element in List
0 points
In this article, we would like to show you how to find an element in List in Java 8.
In this approach we're gonna:
- invoke
stream()
on the list, - call
collect()
method withCollector.toList()
that collects all Stream elements into a List instance.
In this example, we use Java 8 Stream API to find the first occurrence of User named Tom
in the List.
xxxxxxxxxx
1
import java.io.IOException;
2
import java.util.ArrayList;
3
import java.util.Arrays;
4
import java.util.List;
5
import java.util.stream.Collectors;
6
7
public class Example {
8
9
public static void main(String[] args) throws IOException {
10
11
// Create list of users --------------------
12
List<User> users = new ArrayList<>(Arrays.asList(
13
new User("Tom", 20),
14
new User("Kate", 21),
15
new User("Ann", 22)
16
));
17
18
// find an element in List --------------------
19
20
List<User> foundUsers = users.stream()
21
.filter(user -> "Tom".equals(user.getName()))
22
.collect(Collectors.toList());
23
24
System.out.println(foundUsers);
25
}
26
}
Output:
xxxxxxxxxx
1
User{ name='Tom', age=20 }
Note:
We create new list -
foundUsers
to collect the result in case there are many users namedTom
.
Note:
In the section below you can find the implementation of the User class
User.java:
xxxxxxxxxx
1
public class User {
2
private final String name;
3
private final int age;
4
5
public User(String name, int age) {
6
this.name = name;
7
this.age = age;
8
}
9
10
public String getName() {
11
return name;
12
}
13
14
15
public String toString() {
16
return "User{ " +
17
"name='" + name + '\'' +
18
", age=" + age +
19
" }";
20
}
21
}