Let's say I have a list of objects - Student(s). Each student object has various properties - roll number, class name (Not to be confused with Java class name, this is student's class name), student name etc.
The requirement is to retrieve student objects which have class name say "stack overflow". We may create a hashmap with classname (String) and it's respective student object. Is there any other solution in java which does not use hashmap? I have come across various requirements like these where generally I create an hashmap and move ahead. I'm just curious if there is a better way to solve problems like these.
Using java 8 stream api
Student result1 = list.stream() // Convert to steam
.filter(x -> "rahul".equals(x.getName())) // we want "rahul" only
.findAny() // If 'findAny' then return found
.orElse(null);
And to collect list
List<Student> result1 = list.stream() // Convert to steam
.filter(x -> "rahul".startsWith(x.getName()))
.collect(Collectors.toList());
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments