数据准备
List<BookEntity> bookEntityList = new ArrayList<>();
BookEntity bookEntity = BookEntity.builder().bookName("钢铁是怎样炼成的").bookOwner("xinliushijian").build();
BookEntity bookEntity1 = BookEntity.builder().bookName("悲惨世界").bookOwner("xinliu").build();
BookEntity bookEntity2 = BookEntity.builder().bookName("笑面人").bookOwner("shijian").build();
BookEntity bookEntity3 = BookEntity.builder().bookName("笑面人").bookOwner("shijian1").build();
bookEntityList.add(bookEntity);
bookEntityList.add(bookEntity1);
bookEntityList.add(bookEntity2);
bookEntityList.add(bookEntity3);
场景1. key和value都是对象中的某个属性值
方法1(有key冲突问题)
Map<String, String> bookNameOwnerMap = bookEntityList.stream()
.collect(Collectors.toMap(BookEntity::getBookName, BookEntity::getBookOwner));
方法2(正确用法)
加上key冲突处理函数
// 当key冲突时选择第二个key值覆盖第一个key值
Map<String, String> bookNameOwnerMap = bookEntityList.stream()
.collect(Collectors.toMap(BookEntity::getBookName, BookEntity::getBookOwner, (oldValue, newValue) -> newValue));
打印结果
{
"悲惨世界":"xinliu",
"钢铁是怎样炼成的":"xinliushijian",
"笑面人":"shijian1"
}
场景2. key是对象中的某个属性值,value是对象本身(使用返回本身的lambda表达式)
如果不正确指定Collectors.toMap方法的第三个参数(key冲突处理函数),
那么在key重复的情况下该方法会报出【Duplicate Key】的错误导致Stream流异常终止,使用时要格外注意这一点
方法1(有key冲突问题)
Map<String, BookEntity> bookNameEntityMap = bookEntityList.stream()
.collect(Collectors.toMap(BookEntity::getBookName, entity -> entity));
方法2(有key冲突问题)
使用Function.identity()的简洁写法
Map<String, BookEntity> bookNameEntityMap = bookEntityList.stream()
.collect(Collectors.toMap(BookEntity::getBookName, Function.identity()));
方法3(正确用法)
使用Function.identity(), 加上key冲突处理函数
// 当key冲突时选择第二个key值覆盖第一个key值
Map<String, BookEntity> bookNameEntityMap = bookEntityList.stream()
.collect(Collectors.toMap(BookEntity::getBookName, Function.identity(), (oldValue, newValue) -> newValue));
打印结果
{
"悲惨世界":{
"bookName":"悲惨世界",
"bookOwner":"xinliu",
"bookPress":null,
"bookPrice":null,
"bookType":null
},
"钢铁是怎样炼成的":{
"bookName":"钢铁是怎样炼成的",
"bookOwner":"xinliushijian",
"bookPress":null,
"bookPrice":null,
"bookType":null
},
"笑面人":{
"bookName":"笑面人",
"bookOwner":"shijian1",
"bookPress":null,
"bookPrice":null,
"bookType":null
}
}
pojo
import lombok.Builder;
import lombok.Data;
@Data
@Builder
public class BookEntity {
// 书名
String bookName;
// 价格
String bookPrice;
// 所有人
String bookOwner;
// 出版社
String bookPress;
// 类型
String bookType;
}
格式化打印
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.JSON;
public class FastJsonFormatPrintUtils {
public static void formatPrint(Object object) {
String pretty = JSON.toJSONString(object, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue,
SerializerFeature.WriteDateUseDateFormat);
System.out.println(pretty);
}
}