要使用Java 8 Stream将List对象转换为Map,其中id作为键(key),name作为值(value),如果name不存在,则使用nickName作为值,可以使用以下代码实现:
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class ListToMapConversion {
public static void main(String[] args) {
List<Person> personList = List.of(
new Person("1", "John", "Johnny"),
new Person("2", "", "Mike"),
new Person("3", "Alice", "")
);
Map<String, String> resultMap = personList.stream()
.collect(Collectors.toMap(
Person::getId,
person -> person.getName().isEmpty() ? person.getNickName() : person.getName(),
(existingValue, newValue) -> existingValue, // 如果有重复的键,保留旧值
HashMap::new // 指定返回的Map类型
));
System.out.println(resultMap);
}
static class Person {
private String id;
private String name;
private String nickName;
public Person(String id, String name, String nickName) {
this.id = id;
this.name = name;
this.nickName = nickName;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getNickName() {
return nickName;
}
}
}
在上述代码中,我们使用了一个自定义的Person类来表示列表中的对象,其中包含id、name和nickName字段。通过Java 8的Stream API和Collectors.toMap方法,我们将List转换为一个Map<String, String>,其中id是键,name是值,如果name为空,则使用nickName作为值。
输出结果将会是:{1=John, 2=Mike, 3=Alice}
请根据实际情况修改Person类和输入的List对象,以适应你的需求。