lpdd lpdd - 1 year ago 71
Java Question

How to Loop next element in hashmap

I have a set of strings like this

A_2007-04, A_2007-09, A_Agent, A_Daily, A_Execute, A_Exec, B_Action, B_HealthCheck

I want output as:

Key = A, Value = [2007-04,2007-09,Agent,Execute,Exec]
Key = B, Value = [Action,HealthCheck]

I'm using HashMap to do this

count:total no of strings
reports:set of strings

Logic I used is nested loop:

for (String l : reports[i]) {
for (String r : pckg) {
String[] g = l.split("_");
if (g[0].equalsIgnoreCase(r)) {
dirFiles.put(g[0], report);
} else {

I'm getting output as

Key = A, Value = [2007-04,2007-09,Agent,Execute,Exec]

How to get second key?
Can someone suggest logic for this?

Answer Source

In terms of raw code this should do what I think you are trying to achieve:

// Create a collection of String any way you like, but for testing
// I've simply split a flat string into an array.
String flatString = "A_2007-04,A_2007-09,A_Agent,A_Daily,A_Execute,A_Exec,"
        + "P_Action,P_HealthCheck";
String[] reports = flatString.split(",");

Map<String, List<String>> mapFromReportKeyToValues = new HashMap<>();

for (String report : reports) {
    int underscoreIndex = report.indexOf("_");
    String key = report.substring(0, underscoreIndex);
    String newValue = report.substring(underscoreIndex + 1);
    List<String> existingValues = mapFromReportKeyToValues.get(key);
    if (existingValues == null) {
        // This key hasn't been seen before, so contain a new list
        // to contain values which belong under this key.
        existingValues = new ArrayList<>();
        mapFromReportKeyToValues.put(key, existingValues);

System.out.println("Generated map:\n" + mapFromReportKeyToValues);

Though I recommend tidying it up and organising it into a method or methods as fits your project code.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download