Untitled
unknown
plain_text
a year ago
1.1 kB
11
Indexable
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Main {
public static void main(String[] args) {
// Original map with String keys and List<String> values
Map<String, List<String>> mapWithList = new HashMap<>();
mapWithList.put("key1", List.of("value1", "value2"));
mapWithList.put("key2", List.of("value3", "value4"));
mapWithList.put("key3", List.of("value5"));
// New map with String keys and String values
Map<String, String> mapWithFirstValue = new HashMap<>();
// Iterate through the original map and take the first value from each list
for (Map.Entry<String, List<String>> entry : mapWithList.entrySet()) {
String key = entry.getKey();
List<String> valueList = entry.getValue();
if (valueList != null && !valueList.isEmpty()) {
mapWithFirstValue.put(key, valueList.get(0));
}
}
// Print the new map
System.out.println(mapWithFirstValue);
}
}
Editor is loading...
Leave a Comment