Home > Back-end >  Iterate Map of String and List of integer with not fixed values
Iterate Map of String and List of integer with not fixed values

Time:03-22

I have a Map of String and List counts.I want to iterate this and want to set map values in an object.

    counts.put("ABC", Arrays.asList(1,2,3));
    counts.put("XYZ", Arrays.asList(1,2));
    counts.put("PQR", Arrays.asList(1));
    counts.put("IJK", Arrays.asList());

map values are of list type and it can be 1,2,3 etc. or empty but will not exceed 3 in short size can not be more than 2.

I have written code like below:

for (Map.Entry<String,List<Integer>> count : counts.entrySet()) {
        InventoryOwnerManagerResult result = new InventoryOwnerManagerResult();
        InventoryOwnerPresence  presence = new InventoryOwnerPresence();
        switch (count.getValue().size()) {
            case 1:
                presence.setConfigCount(count.getValue().get(0));
                presence.setWebsitesCount(0);
                presence.setSourcesCount(0);
                break;
            case 2:
                presence.setConfigCount(count.getValue().get(0));
                presence.setWebsitesCount(count.getValue().get(1));
                presence.setSourcesCount(0);
                break;
            case 3:
                presence.setConfigCount(count.getValue().get(0));
                presence.setWebsitesCount(count.getValue().get(1));
                presence.setSourcesCount(count.getValue().get(2));
                break;
            default:
                presence.setConfigCount(0);
                presence.setWebsitesCount(0);
                presence.setSourcesCount(0);
                break;
        }
         result.setInventoryOwnerPresence(presence);
    }

This is very old school as well as not an appropriate approach.

Is there any other way to do this?

CodePudding user response:

You can replace the switch with the following:

List<Integer> counts = count.getValue();
presence.setConfigCount(counts.size() > 0 ? counts.get(0) : 0);
presence.setWebsiteCount(counts.size() > 1 ? counts.get(1) : 0);
presence.setSourcesCount(counts.size() > 2 ? counts.get(2) : 0);

This will behave differently if numbers has more than 3 elements; this solution discards only the 4th and later elements, your solution discards all. That doesn't matter though, since you'll never get more than 3 elements.

Which option you chose is personal preference. The switch is clear but verbose, the ternary expressions are concise but may be a bit harder to read for some. As far as performance goes, the switch probably performs better but I doubt you'll really see the difference.

  • Related