0

I have a big LinkedHashMap<Integer,<List<String>>

.

For example:

<86, ["abc","def","xyz"]>  
<32, ["ugy","oop","bbb"]>  
<..., ...........]>

What i want is when user type a Comma separated String(e.g "abc,oop,bbb"), i want to print out the key. In these case keys are 86,32,32. I can handle separete the String into an array by using .split(" "); but i don't know what is simplest way to search these Strings ?

  • I think that list is the wrong data structure to use, if you just want to check whether all strings entered appear somewhere in the list inside your map. – Tim Biegeleisen Mar 30 '17 at 00:32
  • Do you also want to take order into account? I.e. is `abc,def` the same as `def,abc` ? – Tim Biegeleisen Mar 30 '17 at 00:34
  • Which one should i use? I.e Order is matter. If String is `abc,ugy` program should print out `86,32` but If String is `ugy,abc`program should print out `32,86` –  Mar 30 '17 at 00:34
  • Well maybe using a set would make more sense. Then you could just iterate the user's input and check. – Tim Biegeleisen Mar 30 '17 at 00:35
  • Possible duplicate of http://stackoverflow.com/questions/1383797/java-hashmap-how-to-get-key-from-value – Paul Back Mar 30 '17 at 00:36
  • Your question is not specific enough to answer. You need to build a second map as an index that relates values back to keys but to do that you'll need to answer some questions, such as "are the strings in the value lists all unique in the map, or can a string appear more than once anywhere in the map?" If the the answer is that they are unique, the a simple map will suffice, but if not then you'll need another multimap like you already have but this time a `Map>`. – Jim Garrison Mar 30 '17 at 00:48
  • Yeah the Strings in lists are unique. They can't be appear more than once anywhere in the map. –  Mar 30 '17 at 00:55

1 Answers1

0

I would use a map of integers to sets, not lists, since using a set would make checking against the user input without regard to order relatively easy. Doing the same check for a list would be harder.

public Integer getKey(Map<Integer, Set<String>> map, String input) {
    String[] parts = input.split(",");
    for (Map.Entry<Integer, Set<String>> entry : map.entrySet()) {
        Integer key = entry.getKey();
        Set<String> value = entry.getValue();
        if (value.size() != parts.length) {
            continue;
        }
        int counter = 0;
        for (String part : parts) {
            if (value.contains(part)) {
                ++counter;
            }
            else {
                break;
            }
        }
        if (counter == value.size()) {
            return key;
        }
    }

    return null;
}
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360