如何以命令式方式改进这段代码片段?

huangapple go评论70阅读模式
英文:

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&lt;Student&gt; myStudentList = new ArrayList&lt;&gt;();) a possible solution woudl be

final double total = myStudentList.stream()
    .mapToDouble(Studen::getScore)
    .sum();

<kbd>Ideone demo</kbd>

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&lt;?&gt;) myStudentList).stream()
    .filter(o -&gt; o instanceof Student)
    .map(o -&gt; (Student) o)
    .mapToDouble(Studen::getScore)
    .sum();

<kbd>Ideone Demo</kbd>

答案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 -&gt; ((Student) x).getStudentMark()).sum();

If the List was declared with Student as the type parameter, the code would be much improved.

List&lt;Student&gt; myStudentList = new ArrayList&lt;&gt;();
//...
final double total = myStudentList.stream().mapToDouble(Student::getStudentMark).sum();

huangapple
  • 本文由 发表于 2020年8月13日 00:26:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/63380866.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定