在該程序中,您將學(xué)習(xí)將Java map集合轉(zhuǎn)換為列表的各種技巧。
import java.util.*;
public class MapList {
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>();
map.put(1, "a");
map.put(2, "b");
map.put(3, "c");
map.put(4, "d");
map.put(5, "e");
List<Integer> keyList = new ArrayList(map.keySet());
List<String> valueList = new ArrayList(map.values());
System.out.println("Key List: " + keyList);
System.out.println("Value List: " + valueList);
}
}運行該程序時,輸出為:
Key List: [1, 2, 3, 4, 5] Value List: [a, b, c, d, e]
在上面的程序中,我們有一個名為的Integer和String的map集合。由于map包含鍵值對,因此我們需要兩個列表來存儲它們,即keyList鍵和valueList值。
我們使用map的keySet()方法獲取所有鍵,并從它們創(chuàng)建了一個ArrayList keyList。 同樣,我們使用map的values()方法獲取所有值,并從中創(chuàng)建一個ArrayList valueList。
import java.util.*;
import java.util.stream.Collectors;
public class MapList {
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>();
map.put(1, "a");
map.put(2, "b");
map.put(3, "c");
map.put(4, "d");
map.put(5, "e");
List<Integer> keyList = map.keySet().stream().collect(Collectors.toList());
List<String> valueList = map.values().stream().collect(Collectors.toList());
System.out.println("Key List: " + keyList);
System.out.println("Value List: " + valueList);
}
}該程序的輸出與示例1相同。
在上面的程序中,我們沒有使用ArrayList構(gòu)造函數(shù),而是使用stream()將映射轉(zhuǎn)換為list
我們已經(jīng)通過將Collector的toList()作為參數(shù),通過collect()方法將鍵和值轉(zhuǎn)換為流,并將其轉(zhuǎn)換為列表