2

New to Java 8, and am unable to figure this one out. I have two maps of type TreeMap<Long, Integer>, one is called patternMap and the other answerMap.

patternMap is hardcoded to look for a particular pattern of key-value pairs, so there are many patternMap's, and their size is always less than or equal to answerMap. I would like to check which patternMaps are a match in answerMap, and I mean I need exact match on key and value both, not just one.

I'm unable to use the submap method, because patternMap may not have a contiguous range of keys. The obvious way is to walk through the patternMap and check each Map.Entry object with equals method. However, I have many patternMap's to check against a particular answerMap, so I'm curious to know if there is a better way, probably using lambdas/streams. I also cannot modify the answerMap or the patternMap, so this has to be a non-mutating function. I use TreeMap's because the ordering is important for the application.

There is no code here because I haven't found a way to do this, but pseudo-code would look like this:

for every patternMap in the Collection {
   if answerMap contains patternMap, make a note
}

EDIT: Here are some definitions(this isn't working code, but hopefully makes question clearer:

 private static final TreeMap<Long, Integer> patternMap1;
 private static final TreeMap<Long, Integer> patternMap2;
 private static final ArrayList<TreeMap> listOfPatternMaps;
 private TreeMap<Long, Integer> answerMap;

  private Set<TreeMap<Long, Integer>> findPatterns(TreeMap answerMap) {
       this.answerMap = answerMap;
       for(patternMap : listOfPatternMaps) {
           if answerMap contains patternMap {
              make a note
           }
       } 
       return setOfMatchedPatterns;
  }
Misha
  • 27,433
  • 6
  • 62
  • 78
aaaaarrrgghhh
  • 397
  • 5
  • 16
  • When you are doing `if answerMap contains patternMap`, is this referring to all the key-value pairs in the patternMap matching some subset of the answerMap? – smac89 Apr 09 '16 at 07:05
  • It would be helpful to see definitions of answerMap and patternMap, seeing actual code is better then reading about it. – Krzysztof Krasoń Apr 09 '16 at 07:06
  • Possible duplicate of [Combine multiple Collections into a single logical Collection?](http://stackoverflow.com/questions/4896662/combine-multiple-collections-into-a-single-logical-collection) – smac89 Apr 09 '16 at 07:13
  • I hope that edit it pseudocode, because raw `TreeMap` is a big no, no. – Andreas Apr 09 '16 at 07:28
  • @Smac89 - yes, answerMap contains questionID as key and answerChosen as value, and i want to see if the answers match a defined pattern of , so the pattern will be "subset" or submap" of answerMap. – aaaaarrrgghhh Apr 09 '16 at 07:28

1 Answers1

8

This should do the trick:

answerMap.entrySet().containsAll(patternMap.entrySet())
Misha
  • 27,433
  • 6
  • 62
  • 78