Explanation:
In this blog post, we'll dive into Java 8 streams and demonstrate how to filter a list of Student
objects to find students who have a specific book, and then extract their names.
// Create some books and students Book book1 = new Book(1, "Book A"); Book book2 = new Book(2, "Book B"); Book book3 = new Book(3, "Book C");
List<Student> students = new ArrayList<>(); students.add(new Student(1, "Alice", Arrays.asList(book1, book2))); students.add(new Student(2, "Bob", Arrays.asList(book2, book3))); students.add(new Student(3, "Charlie", Arrays.asList(book1, book3))); students.add(new Student(4, "David", Arrays.asList(book2)));
String bookNameToSearch = "Book A";
List<String> studentNamesWithBook =
students.stream().filter( s -> s.getBooks().stream().anyMatch(b -> b.getName().equals(bookNameToSearch))) .map(Student::getName).collect(Collectors.toList());
Sample Code:
javaimport java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; class Book { private int id; private String name; public Book(int id, String name) { this.id = id; this.name = name; } public String getName() { return name; } } class Student { private int id; private String name; private List<Book> books; public Student(int id, String name, List<Book> books) { this.id = id; this.name = name; this.books = books; } public String getName() { return name; } public List<Book> getBooks() { return books; } } public class StudentBookSearch { public static void main(String[] args) { // Create some books and students Book book1 = new Book(1, "Book A"); Book book2 = new Book(2, "Book B"); Book book3 = new Book(3, "Book C"); List<Student> students = new ArrayList<>(); students.add(new Student(1, "Alice", Arrays.asList(book1, book2))); students.add(new Student(2, "Bob", Arrays.asList(book2, book3))); students.add(new Student(3, "Charlie", Arrays.asList(book1, book3))); students.add(new Student(4, "David", Arrays.asList(book2))); String bookNameToSearch = "Book A"; List<String> studentNamesWithBook = students.stream().filter( s -> s.getBooks().stream().anyMatch(b -> b.getName().equals(bookNameToSearch))) .map(Student::getName).collect(Collectors.toList()); System.out.println("Students with the book '" + bookNameToSearch + "': " + studentNamesWithBook); } }
Sample Output:
arduinoStudents with the book 'Book A': [Alice, Charlie]
Comments
Post a Comment