0

so basically, I'm trying to parse through each map entry of a HashMap while also reading each string value in the String array. I will then use each of those string values in the array as parameters for specific methods. Now, I know how to parse through each map entry, it's just the iterating through the string array in the map that's confusing me. Any advice?

My code:

HashMap<String,String[]> roomSite = new HashMap<String, String[]>();

Set set = roomSite.entrySet();

Iterator<Map.Entry<String, String[]>> iterator = set.iterator();

while(iterator.hasNext()) {
    Map.Entry mentry = (Map.Entry)iterator.next();
        System.out.print("key is: "+ mentry.getKey() + " & Value is: ");
        System.out.println(Arrays.deepToString((String[]) mentry.getValue()));
}

Output:

key is: 0 & Value is: [wall, d0, wall, wall]
key is: 1 & Value is: [d0, wall, d1, wall]
key is: 2 & Value is: [wall, wall, wall, d1]
1
  • 1
    java has moved out of the dark ages of horrible casts such as the first line in your while loop. Rather than using iterators to cycle through, why not use the more idiomatic for(String key : roomSite.keys()) { String[] stringList = roomSite.get(key); for (String s : stringList) { // do what you will with s } } Commented Nov 10, 2015 at 2:54

2 Answers 2

1

You already have the String array, just assign it to a variable:

String[] stringArray = (String[]) mentry.getValue();

for (String str : stringArray){
    // process str
}
Sign up to request clarification or add additional context in comments.

1 Comment

You may not need the cast
0

Solution using Java 8 stream feature

HashMap<String,String[]> roomSite = new HashMap<>();
roomSite.put("1",new String[]{"Hello","World"});
roomSite.put("2",new String[]{"India","Germany"});

//This is to print all value for given key but if you want process for each key with all value then put ur logic into forEach
roomSite.entrySet().stream().map(entry -> "key is: "+entry.getKey() + " & Value is: " + Arrays.stream(entry.getValue())
        .collect(Collectors.joining(","))).forEach(System.out::println);

//This logic emits entry for key and value from array, basically you will have pair of key and value which can be used for processing
roomSite.entrySet().stream().flatMap(entry-> Arrays.stream(entry.getValue()).map(value->new AbstractMap.SimpleEntry<>(entry.getKey(),value))).forEach(simpleEntry-> {
    final String key= simpleEntry.getKey();
    final String value= simpleEntry.getValue();
    System.out.println("Key : "+ key+" , value : "+ value);

    //process ur logic
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.