英文:
Java move private function into setter
问题
以下是您要翻译的代码部分:
public TestResponse build(Map<String, List<TestRequest>> testRequestMap) {
return TestResponseBuilder.builder()
.tests(getTestResponses(testRequestMap))
.build();
}
private List<Test> getTestResponses(Map<String, List<TestRequest>> testRequestMap) {
List<Test> tests = new ArrayList<Test>();
testRequestMap.keySet().stream().forEach(t -> {
Test test = new Test();
test.setTest(t);
tests.add(test);
});
return test;
}
希望这有助于您的工作。如果您有任何其他问题,请随时提出。
英文:
I have the following code. Is there a way to avoid writing a separate private method and have this logic embedded in the .tests setter (I am using Lombok's builder).
public TestResponse build(Map<String, List<TestRequest> testRequestMap) {
return TestResponseBuilder.builder()
.tests(getTestResponses(testRequestMap))
.build();
}
private List<Test> getTestResponses(Map<String, List<TestRequest> testRequestMap) {
List<Test> tests = new ArrayList<Test>();
testRequestMap.keySet().stream().forEach( t -> {
Test test = new Test();
test.setTest(t);
tests.add(test);
});
return test;
}
Thanks
Ram
答案1
得分: 3
目前情况下是无法做到的,因为在方法中有多于一个语句。
不过,你可以将其写成:
return testRequestMap.keySet().stream()
.map(t -> {
Test test = new Test();
test.setTest(t);
return test;
})
.collect(Collectors.toList());
然后可以直接将其内联到 `.tests(...)` 方法调用中作为参数。
return TestResponseBuilder.builder()
.tests(
testRequestMap.keySet().stream()
.map(t -> {
Test test = new Test();
test.setTest(t);
return test;
})
.collect(Collectors.toList())
.build();
但实际上,这比你当前的做法更糟糕。
英文:
As it stands, you can't, because you have more than one statement in the method.
However, you can write it as:
return testRequestMap.keySet().stream()
.map(t -> {
Test test = new Test();
test.setTest(t);
return test;
})
.collect(Collectors.toList());
This can then be inlined directly into the .tests(...)
method call as a parameter.
return TestResponseBuilder.builder()
.tests(
testRequestMap.keySet().stream()
.map(t -> {
Test test = new Test();
test.setTest(t);
return test;
})
.collect(Collectors.toList())
.build();
but really, this is worse than what you currently have.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论