English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutoriel de base Java

Java 流程控制

Java 数组

Java 面向对象(I)

Java 面向对象(II)

Java 面向对象(III)

Gestion des exceptions Java

Java 列表(List)

Java Queue(队列)

Java Map集合

Java Set集合

Java 输入输出(I/O)

Java Reader/Writer

Java 其他主题

Java程序将集合(HashMap)转换为列表

Comprehensive Java examples

在该程序中,您将学习将Java map集合转换为列表的各种技巧。

示例1:将map转换为列表

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, \
        map.put(3, \
        map.put(4, \
        map.put(5, \
        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()方法获取所有键,并从它们创建了一个ArrayList keyList。 同样,我们使用map的values()方法获取所有值,并从中创建一个ArrayList valueList。

示例2:使用流将map转换为列表

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, \
        map.put(3, \
        map.put(4, \
        map.put(5, \
        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);
    }
}

The output of this program is similar to the example1The same.

In the above program, we did not use the ArrayList constructor, but used stream() to convert the map to a list

We have passed to the toList() of Collector as a parameter, converted the key and value to a stream through the collect() method, and then converted it to a list

Comprehensive Java examples