代码
实体类
@Data @AllArgsConstructor @NoArgsConstructor public class TestEntity { private String no1; private String no2; private String no3; private String no4; }
实现代码
public class TestStream { public static void main(String[] args) { /*数据准备*/ List<TestEntity> list = new ArrayList<>(); for (int i = 0; i < 4; i++) { TestEntity entity = new TestEntity("test0"+i,"test0"+i,"test0"+i,"test0"+i); list.add(entity); } /*stream测试*/ /*01.List<T> 转换为 Map<String,List<T>>*/ Map<String, List<TestEntity>> collect01 = list.stream().collect(Collectors.groupingBy(TestEntity::getNo1)); /*02.List<T> 转换为 Map<?,?>*/ Map<String, String> collect02 = list.stream().collect(Collectors.toMap(TestEntity::getNo1, TestEntity::getNo2)); /*03.List<T> 转换为 Map<?,T>*/ Map<String, TestEntity> collect03 = list.stream().collect(Collectors.toMap(TestEntity::getNo1, val -> val)); Map<String, TestEntity> collect04 = list.stream().collect(Collectors.toMap(TestEntity::getNo1, Function.identity())); /*04.List<T> 转换为 List<?>*/ List<String> collect05 = list.stream().map(TestEntity::getNo1).collect(Collectors.toList()); } }
结果
01.List 转换为 Map<String,List>
02.List 转换为 Map<?,?>
03.List 转换为 Map<?,T>
04.List 转换为 List<?>