我对该Function.identity()方法的用法有疑问.
想象一下以下代码:
Arrays.asList("a", "b", "c")
.stream()
.map(Function.identity()) // <- This,
.map(str -> str) // <- is the same as this.
.collect(Collectors.toMap(
Function.identity(), // <-- And this,
str -> str)); // <-- is the same as this.
Run Code Online (Sandbox Code Playgroud)
是否有任何理由你应该使用Function.identity()而不是str->str(反之亦然).我认为第二种选择更具可读性(当然是品味问题).但是,有没有"真正的"理由为什么应该首选?
我正在寻找一种优雅的方式来创建一个依赖注入工厂.在我的例子中,工厂只需要调用一个参数构造函数.我发现这个答案概述了如何将a Function<ParamType, ClassToNew>用于此类目的.
但我的问题是:在我的情况下,我的ctor声明抛出一些检查异常.
我没有得到:使用对该构造函数的方法引用创建该函数不起作用.如:
import java.util.function.Function;
public class Mcve {
public Mcve(String s) throws Exception {
// whatever
}
public static void main(String[] args) {
Function<String, Mcve> mcveFactory = Mcve::new;
}
}
Run Code Online (Sandbox Code Playgroud)
告诉我"未处理的异常:java.lang.Exception" Mcve::new.虽然这段代码没有调用构造函数.
两个问题:
throws Exception到我main()并没有帮助)在Java中,是否有一种单行方式来创建一个用对象的n个克隆初始化的集合?
我想要相当于这个:
foo = vector<vector<int> >(10); c ++,创建10个不同的空向量[ [] for i in range(10) ] Python,一个由10个不同的空数组组成的数组Array.new(10) { [] } Ruby,与Python相同在Java中,我只找到了
new ArrayList<ArrayList<Integer> >(Collections.nCopies(10, new ArrayList<Integer>()))
Run Code Online (Sandbox Code Playgroud)
然而,这并不等同于其他的例子,因为名单别名.
有没有办法创建一个不同的对象克隆数组,而不使用for循环,最好不要求助于外部库?
我有员工类:
public class Employee {
private Long id;
private String name;
private String externalId;
public Employee(Long id, String name, String externalId) {
this.id = id;
this.name = name;
this.externalId = externalId;
}
//getters, setter
}
Run Code Online (Sandbox Code Playgroud)
返回员工的员工服务(可以为NULL).
private void performEmployeeProcessing() {
Long employeeId = 2L;
Object o = Optional.ofNullable(employeeService.getById(employeeId))
.orElseGet(Employee::new, 1L, "", "");
System.out.println(o);
}
Run Code Online (Sandbox Code Playgroud)
它说编译错误
Employee :: new,1L,"",""
无法解析构造函数.