Jerry
Jerry

Reputation: 393

Compare map key with a list of strings

can map be compare with arraylist of string in java

private Map<String, String> checkInScopeLobs(Map<String, String> allLobsChkBx)
    {
        Map<String, String> inScopeLobs = new HashMap<String, String>();; 
        for (Map.Entry<String, String> entry : allLobsChkBx.entrySet())
        {
          if(entry.getKey().contains("1") || entry.getKey().contains("2") || entry.getKey().contains("3")){
              inScopeLobs.put(entry.getKey(), entry.getValue());
          }
        }
        return inScopeLobs;
    }

is this a correct way ?

Upvotes: 1

Views: 8708

Answers (3)

Menno
Menno

Reputation: 12621

You can make use of keySet(). This method returns a Set of keys (for more info, Docs from Oracle about Map). This means less overhead than iterating over your whole map. In the following case you'll only request values of matching keys.

There are some other faults like a double semicolon and since JDK7 you don't have to define your map when initializing.

private Map<String, String> checkInScopeLobs(Map<String, String> allLobsChkBx) {
    Map<String, String> inScopeLobs = new HashMap();
    List<String> keys = Arrays.asList( { "1", "2", "3" } );
    for(String key : allLobsChkBx.keySet()) {
        if(keys.contains(key)) {
            inScopeLobs.put(key, allLobsChkBx.get(key));
        }
    }
    return inScopeLobs;
}

Why aren't you using an Integer instead of a String, since you're only storing numbers.

Upvotes: 2

Eugene
Eugene

Reputation: 530

Actually there are no such methods, but you can try this approach:

Map<String, String> allLobsChkBx = new HashMap<String, String>(4);
allLobsChkBx.put("1", "A");
allLobsChkBx.put("2", "B");
allLobsChkBx.put("3", "C");
allLobsChkBx.put("4", "D");
allLobsChkBx.put("5", "E");

System.out.println("Before retain: " + allLobsChkBx);
List<String> keysToRetain = Arrays.asList(new String[] { "1", "2", "3" });
allLobsChkBx.keySet().retainAll(keysToRetain);
System.out.println("After retain: " + allLobsChkBx);

It will produce following output:

Before retain: {3=C, 2=B, 1=A, 5=E, 4=D}
After retain: {3=C, 2=B, 1=A}

Upvotes: 0

Peeyush
Peeyush

Reputation: 432

Since key is String you can use matches method from String class

for (Map.Entry<String, String> entry : allLobsChkBx.entrySet())
    {
      if(entry.getKey().matches(".*[123].*")){
          inScopeLobs.put(entry.getKey(), entry.getValue());
      }
    }

Upvotes: 0

Related Questions