Search code examples
javahashmaptreemap

Searching a Hashmap for values of type list, retrieving an element of list and adding it to a new Collection to return


i'm pretty new when it comes to Java but i'll hopefully clear this up.

I currently have one class and within that class i have a TreeMap called "departments" which takes an argument of >:

TreeMap <String, List<String>> department;

Within each department such as HR, Builders etc there are a list of names of people who work there. Such as:

HR: Janet, Jones, Bob

What i'd like to do is search through department to find all departments (keys) that contain someone who's called "bob" for instance and add them to a collection to make a return.

Can anyone help with this, i've been pulling my hair out for a few days! So far i'm this far with the method although clearly nowhere near complete!

public List<String> selectValues( String... aValue)

{

for(String eachDept : department.keySet()){
  Collection<String> peopleInTheDept = department.get(eachDept);
  for(String person : aValue){
      if(peopleInTheDept.contains(person)){
          result.add(person);
      }
  }
}
System.out.println(result);
}

Solution

  • Just like OH GOD SPIDERS predicted, there is a Java 8 stream solution:

    TreeMap <String, List<String>> department = new TreeMap<>();
    department.put("AB", Arrays.asList("Bob", "Truus", "Miep"));
    department.put("CD", Arrays.asList("Jan", "Kees", "Huub"));
    department.put("EF", Arrays.asList("Jan", "Piet", "Bert"));
    String aValue = "Jan";
    
    Map<String,List<String>> result = department.entrySet().stream()
    // filter out those departments that don't contain aValue
      .filter(entry -> entry.getValue().contains(aValue))
    // collect the matching departments back into a map 
      .collect(Collectors.toMap(k -> k.getKey(), k -> k.getValue()));
    
    // print the result
    result.forEach((k,v)-> System.out.println(k + " " + v.toString()));
    

    Which prints:

    EF [Jan, Piet, Bert]
    CD [Jan, Kees, Huub]
    

    Pre Java 8 solution:

    Map<String, List<String>> result2 = new TreeMap<>();
    
    for(String eachDept : department.keySet()){
        List<String> peopleInTheDept = department.get(eachDept);
        if(peopleInTheDept.contains(aValue)){
                result2.put(eachDept, department.get(eachDept));
        }
    }
    for (String s : result2.keySet()){
        System.out.println(s + " " + result2.get(s));
    }
    

    This prints exactly the same as my Java 8 code.