使用Java 8将List<String>转换为Map<Label, PasswordField>

3

使用流和收集器生成HashMap是可能的吗? 我尝试了以下代码:

 myList.stream()
.map(Label::new)
.collect(Collectors.toMap(Function.identity(), PasswordField::new))

但显然它不起作用,我尝试了其他解决方案,但都没有成功。您有什么建议吗?


顺便提一下,使用“Label”作为键是危险的。HashMap应该有不可变的键,而“Label”不是其中之一。 - Jai
2个回答

5

PasswordField 类只有一个默认构造函数,这意味着 PasswordField::new 将不起作用,因为它相当于 (Label l) -> new PasswordField(l)。而应该使用值映射器 (Label l) -> new PasswordField() 或者简单的 l -> new PasswordField()


这就引出了一个问题,为什么Labelmap步骤中创建而不是在toMap收集器内部创建,即myList.stream() .collect(Collectors.toMap(Label::new, s -> new PasswordField()))... - Holger

1
正如Aomine所提到的,PasswordField有一个默认的构造函数,因此你代码中提到的PasswordField::new不能工作。请改用l -> new PasswordField()代替:
myList.stream()
    .map(Label::new)
    .collect(Collectors.toMap(Function.identity(), l -> new PasswordField()));

1
很抱歉直言,除了Aomine的回答之外,你没有添加任何有用的内容。 - marsouf

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接