Java 将 MisCourseIdSwitch 列表转换为 Map: 使用 Stream 和 Collectors.toMap()
您可以使用 Java 8 的流(stream)和 Collectors.toMap() 方法来实现将列表转换为 Map 的操作。假设 MisCourseIdSwitch 对象的 sysCourseId 属性和 schoolID 属性都是字符串类型,您可以按照以下方式进行转换:
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<MisCourseIdSwitch> misCourseIdSwitchList = ...; // 假设已经有一个包含 MisCourseIdSwitch 对象的列表
Map<String, MisCourseIdSwitch> misCourseIdSwitchMap = misCourseIdSwitchList.stream()
.collect(Collectors.toMap(
misCourseIdSwitch -> misCourseIdSwitch.getSysCourseId() + misCourseIdSwitch.getSchoolID(),
misCourseIdSwitch -> misCourseIdSwitch
));
// 打印转换后的 Map
misCourseIdSwitchMap.forEach((key, value) -> System.out.println('Key: ' + key + ', Value: ' + value));
}
}
在上述代码中,我们通过 stream() 方法将列表转换为流,然后使用 Collectors.toMap() 方法来创建一个新的 Map。toMap() 方法的第一个参数是 Key 的生成函数,将 MisCourseIdSwitch 对象的 sysCourseId 属性和 schoolID 属性拼接为 Key;第二个参数是 Value 的生成函数,直接使用 MisCourseIdSwitch 对象作为 Value。最后,我们使用 forEach() 方法遍历 Map 并打印其中的 Key 和 Value。
请注意,如果列表中的 MisCourseIdSwitch 对象的 sysCourseId 属性加 schoolID 属性存在重复的情况,将会抛出 IllegalStateException 异常。
原文地址: https://www.cveoy.top/t/topic/p1hb 著作权归作者所有。请勿转载和采集!