How to iterate through LinkedHashMap with lists as values in java

How to iterate through LinkedHashMap with lists as values in java

To iterate through a LinkedHashMap with lists as values in Java, you can use a combination of nested loops. Here's an example of how to do it:

import java.util.*; public class LinkedHashMapExample { public static void main(String[] args) { // Create a LinkedHashMap with lists as values LinkedHashMap<String, List<String>> linkedHashMap = new LinkedHashMap<>(); // Populate the LinkedHashMap with data linkedHashMap.put("Key1", Arrays.asList("Value1", "Value2")); linkedHashMap.put("Key2", Arrays.asList("Value3")); linkedHashMap.put("Key3", Arrays.asList("Value4", "Value5", "Value6")); // Iterate through the LinkedHashMap and its lists of values for (Map.Entry<String, List<String>> entry : linkedHashMap.entrySet()) { String key = entry.getKey(); List<String> values = entry.getValue(); System.out.println("Key: " + key); for (String value : values) { System.out.println(" Value: " + value); } } } } 

In this example:

  1. We create a LinkedHashMap named linkedHashMap where the keys are String and the values are List<String>.

  2. We populate the LinkedHashMap with sample data, where each key is associated with a list of values.

  3. We use a for loop to iterate through the LinkedHashMap using entrySet(), which provides access to both keys and values.

  4. For each entry, we retrieve the key and the list of values. We then print the key and iterate through the list of values, printing each value.

The output of the code will be:

Key: Key1 Value: Value1 Value: Value2 Key: Key2 Value: Value3 Key: Key3 Value: Value4 Value: Value5 Value: Value6 

This code demonstrates how to iterate through a LinkedHashMap with lists as values and access both the keys and the values contained within the lists.


More Tags

xsd.exe overflow unicode-escapes angular-ui subclass next.js kendo-chart requestdispatcher clipboard.js gson

More Java Questions

More Bio laboratory Calculators

More Weather Calculators

More Other animals Calculators

More Statistics Calculators