NullPointer
NullPointer

Reputation: 261

Searching a value in a nested Map in Java8

I am trying to look through a nested map for a specific value using java8. Example: The map is a

Map<Integer, Map<String,String>> classStudentGrp;

and some of the records are like

StudentId1:
StudentName:Andy
StudentAge:12
StudentAddress:xxxx

StudentId1:
StudentName:Anna
StudentAge:11
StudentAddress:yyyy

and so on.

I am looking at something like

classStudentGrp.forEach((sid,stu)->stu.forEach((sAttr,val)->val.equals("Andy")));

and I want to either return a boolean (true) or set a variable if 'Andy' is found. I know the traditional approach using entry keys and values, but trying to do this in lambda.

Upvotes: 0

Views: 2080

Answers (3)

GBlodgett
GBlodgett

Reputation: 12819

I highly recommend you create a Student class instead of just having a String in the format:

StudentId1:
StudentName:Andy
StudentAge:12
StudentAddress:xxxx

Java is an Object Oriented language, and it is best to use it as such. You can create a class like:

class Student {
   private String name;
   private String id;
   private int age;
   private String address;  
   //Getters and setters
   //Appropriate constructors
}

Then you could do:

boolean value = classStudentGrp.values().stream()
                                        .anyMatch(e -> e.getName().equals("Andy"));

Which will take a Stream of the values of classStudentGrp (The Map<String, Student), take the values of that Map (A Stream<Students>) and then use anyMatch to determine if any of the Students have the name "Andy"

Upvotes: 2

Samuel Philipp
Samuel Philipp

Reputation: 11050

You can test it with this:

boolean contains = classStudentGrp.values().stream()
        .anyMatch(m -> m.containsValue("Andy"));

But you should use a Student object like this:

public class Student {
    private String name;
    private int age;
    // ...
}

With a List<Student> you can use just this:

boolean contains = classStudentGrp.stream().anyMatch(s -> "Andy".equals(s.getName()))

Upvotes: 1

Qingfei Yuan
Qingfei Yuan

Reputation: 1212

refer to below example

List<String> result = lines.stream()                // convert list to stream
  .filter(line -> "mkyong".equals(line))            // we dont like mkyong
  .collect(Collectors.toList()); 

coming from https://www.mkyong.com/java8/java-8-streams-filter-examples/

Upvotes: 0

Related Questions