-1

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.");
Ah Kang
  • 11
  • 6
  • `double total = myStudentList.stream().mapToDouble(Student::getStudentMark).sum();` – Turing85 Aug 12 '20 at 16:32
  • Also, [the use of raw types is highly discouraged](https://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it#:~:text=A%20%22raw%20type%22%20is%20the,were%20updated%20to%20use%20generics.) (`ArrayList myStudentList = new ArrayList();` -> `ArrayList myStudentList = new ArrayList<>();`). Otherwise, using the stream API will involve at least a type cast and possibly an additional filter step. – Turing85 Aug 12 '20 at 16:37

2 Answers2

2

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();

Ideone demo

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();

Ideone Demo

Turing85
  • 18,217
  • 7
  • 33
  • 58
0

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();
Unmitigated
  • 76,500
  • 11
  • 62
  • 80