效果图
代码
package springboot; import org.junit.Test; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * @author yourheart * @Description * @create 2022-06-12 21:06 */ public class GoodsTests { @Test public void test001(){ // 创建一个List集合 List<FruitDTO> dtoList = Arrays.asList( new FruitDTO("apple", 5), new FruitDTO("banana", 6), new FruitDTO("orange", 6), new FruitDTO("grape", 5), new FruitDTO("kiwi", 4) ); // 将List<FruitDTO>转换为Map,以DTO的name作为key,DTO对象本身作为value Map<String, FruitDTO> dtoMap = dtoList.stream() .collect(Collectors.toMap( FruitDTO::getName, // key是FruitDTO对象的name属性 dto -> dto // value是FruitDTO对象本身 )); // 输出转换后的Map dtoMap.forEach((name, dto) -> System.out.println(name + ": " + dto)); Map<String, Integer> collect = dtoList.stream().collect( Collectors.toMap(FruitDTO::getName, FruitDTO::getLength) ); collect.forEach((name, length) -> System.out.println(name + ": " + length)); } } class FruitDTO { private String name; private int length; public FruitDTO(String name, int length) { this.name = name; this.length = length; } public String getName() { return name; } public int getLength() { return length; } @Override public String toString() { return "FruitDTO{" + "name='" + name + '\'' + ", length=" + length + '}'; } }
用到的pom依赖
<!--引入junit单元测试依赖--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.2</version> </dependency>
标签:map,name,stream,Map,list,length,FruitDTO,public From: https://www.cnblogs.com/q202105271618/p/18182029