How do you find the sum of all numbers in a set in Java? [duplicate]
问题 This question already has answers here : Is there possibility of sum of ArrayList without looping (13 answers) Closed 1 year ago . How would you find the sum of the elements of a set in Java? Would it be the same with an array? In python, I could do: my_set = {1, 2, 3, 4} print(sum(my_set)) 回答1: Aside from using loops explicitly, for List<Integer> list you can do: int sum = list.stream().mapToInt(Integer::intValue).sum(); If it's an int[] ar then do: int sum = IntStream.of(ar).sum(); This is