我是Java Lambda函数的新手,所以这个问题可能很简单.
我有一个实体类,并使用Lombok:
@Entity
@Data
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
// getter & setters
...
}
然后,我得到了Set<String> data
,那里的每个元素代表Product
的名字.现在我想把这个data
转换成Set<Product> prodcts
.我试了两件事:
- 我首先try 使用
Product
的构造函数:
Set<String> data = getData();
//Compiler error:reason: no instance(s) of type variable(s) exist so that String conforms to Product
var products = data.stream().map(Product::new)
但是我不确定如何通过这个Lambda系统错误将参数传递给构造函数,如代码所示.
- 然后,我try 直接调用该方法:
Set<String> data = getData();
//Compiler error: Incompatible types: expected not void but compile-time declaration for the method reference has void return type
var products = data.stream().map(Product::setName)
但是我得到了编译器错误Incompatible types: expected not void but compile-time declaration for the method reference has void return type
.
那么,使用Lambda函数进行这种转换的正确方式是什么呢?