본문 바로가기
Java

[Java] 배열의 합계 얻기

by jn4624 2022. 4. 28.
반응형

1. For문

public class Test {
	public static void main(String[] args) {
		int[] arr = {1,2,3,4,5,6,7,8,9};
		
		int sum = 0;
		for( int i=0; i<arr.length; i++ ) {
			sum += arr[i];
		}
		
		System.out.println(sum);
	}
}

 

2. stream() & parallel()

public class Test {
	public static void main(String[] args) {
		int[] arr = {1,2,3,4,5,6,7,8,9};
		
		int sum = Arrays.stream(arr).parallel().reduce(0,  (a,b) -> a+b);
		
		System.out.println(sum);
	}
}

 

3. reduce()

public class Test {
	public static void main(String[] args) {
		int[] arr = {1,2,3,4,5,6,7,8,9};
		
		int sum = Arrays.stream(arr).reduce(0,  (a,b) -> a+b);
		
		System.out.println(sum);
	}
}

 

4. sum()

public class Test {
	public static void main(String[] args) {
		int[] arr = {1,2,3,4,5,6,7,8,9};
		
		int sum = Arrays.stream(arr).sum();
		
		System.out.println(sum);
	}
}

 

5. IntStream 인터페이스

import java.util.stream.IntStream;

public class Test {
	public static void main(String[] args) {
		int[] arr = {1,2,3,4,5,6,7,8,9};
		
		int sum = IntStream.of(arr).sum();
		
		System.out.println(sum);
	}
}

 

 

🙏 참조 ::

반응형

'Java' 카테고리의 다른 글

[Java] 배열 자르기  (0) 2022.04.28
[Java] ArrayList 정렬(오름차순, 내림차순)  (0) 2022.04.28
[Java] Map To JSONObject  (0) 2022.04.28
[Java] JsonString To Map & JsonString To List Map  (0) 2022.04.28
[Java] Map - getOrDefault 메소드  (0) 2022.04.26