Java How To Convert Map Values To List In Java Some Different Ways Below are some common methods for doing so:
1. How to use values() with ArrayList
You can convert the values of a Map to a List in Java using various approaches.
below are a few common methods:
1. Using ArrayList andvalues()
import java.util.*;
public class MapToListExample {
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>();
map.put(1, "Apple");
map.put(2, "Banana");
map.put(3, "Cherry");
// Convert values to List
List<String> list = new ArrayList<>(map.values());
System.out.println(list); // Output: [Apple, Banana, Cherry]
}
}
2. Using Java 8 Stream API
import java.util.*;
import java.util.stream.Collectors;
public class MapToListExample {
public static void main(String[] args) {
Map<Integer, String> map = Map.of(1, "Apple", 2, "Banana", 3, "Cherry");
// Convert values to List using Stream
List<String> list = map.values().stream().collect(Collectors.toList());
System.out.println(list); // Output: [Apple, Banana, Cherry]
}
}
3. Using forEach Loop
import java.util.*;
public class MapToListExample {
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>();
map.put(1, "Apple");
map.put(2, "Banana");
map.put(3, "Cherry");
List<String> list = new ArrayList<>();
map.values().forEach(list::add);
System.out.println(list); // Output: [Apple, Banana, Cherry]
}
}
💡 Choose the method based on your Java version:
- Use
ArrayList<>(map.values())
for simple cases. - Use Stream API (
map.values().stream().collect(Collectors.toList())
) in Java 8+ for a functional approach. - Use a
forEach
loop if modifying the list during iteration.
- package com.instanceofjavaforus;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- public class MapValueToList {
- Map<Integer, String> map;
- public MapKeyToList(Map<Integer, String> map) {
- this.map = map;
- }
- public List<String> convertValuesToList() {
- return new ArrayList(map.values());
- }
- public static void main(String[] args) {
- Map<Integer, String> map = new HashMap<>();
- map.put(1, "one");
- map.put(2, "two");
- map.put(3, "three");
- map.put(4, "Four");
- map.put(5, "Five");
- map.put(6, "Six");
- map.put(7, "Seven");
- map.put(8, "Eight");
- map.put(9, "Nine");
- map.put(10, "Ten");
- MapValueToList conv = new MapValueToList (map);
- List<String> keysList = conv.convertValuesToList();
- System.out.println("Values:");
- for (String val : keysList) {
- System.out.println(val);
- }
- }
- }
- OutPut:
- Values:
- one
- two
- three
- Four
- Five
- Six
- Seven
- Eight
- Nine
- Ten
Map map = new HashMap<>(); this statement will work from java 7
ReplyDelete