英文:
How to improve this code snippet in imperative way?
问题
以下是翻译好的部分:
以下代码片段具有访问全局变量的副作用,我该如何改进这个代码片段?
double total = 0;
for (Student s : myStudentList){
total = total + s.getSchScore();
}
System.out.println(total + " is total marks.");
英文:
The code snippet below has accessing global variable side affect, how can I improve this code snippet?
double total = 0;
for (Student s : myStudentList){
total = total + s.getSchScore();
}
System.out.println(total + " is total marks.");
答案1
得分: 2
Sure, here's the translated code portion:
如果你愿意/能够输入列表 (ArrayList<Student> myStudentList = new ArrayList<>();
),可能的解决方案是
final double total = myStudentList.stream()
.mapToDouble(Student::getScore)
.sum();
如果你必须/想要继续使用原始类型列表(这是强烈不推荐的),那么我建议两个额外的步骤:过滤掉所有非Student
对象并将对象强制转换为Student
:
final double total = ((List<?>) myStudentList).stream()
.filter(o -> o instanceof Student)
.map(o -> (Student) o)
.mapToDouble(Student::getScore)
.sum();
英文:
If you are willing/able to type the list (ArrayList<Student> myStudentList = new ArrayList<>();
) a possible solution woudl be
final double total = myStudentList.stream()
.mapToDouble(Studen::getScore)
.sum();
If you must/want to continue with the raw type list (which is highly discouraged), then I would recommend two additional steps: filter out all non-Student
-objects and cast the objects to Student
:
final double total = ((List<?>) myStudentList).stream()
.filter(o -> o instanceof Student)
.map(o -> (Student) o)
.mapToDouble(Studen::getScore)
.sum();
答案2
得分: 0
使用原始类型是强烈不推荐的,因为它需要将每个对象转换为所需的类型。
如果List
声明为具有Student
作为类型参数,代码将得到很大的改善。
英文:
Using raw types is strongly discouraged, as it requires casting each Object to the required type.
final double total = myStudentList.stream().mapToDouble(x -> ((Student) x).getStudentMark()).sum();
If the List
was declared with Student
as the type parameter, the code would be much improved.
List<Student> myStudentList = new ArrayList<>();
//...
final double total = myStudentList.stream().mapToDouble(Student::getStudentMark).sum();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论