• Home

My Codegate

  • Home

자바 Stack 합계 구하는 방법

2023/12/18 Posted by Codegate Java No Comments
import java.util.Stack;

public class Sample {

  public static void main(String[] args) {
    Stack<Integer> stack = new Stack<>();
    stack.push(1);
    stack.push(2);
    stack.push(3);

    int sum = 0;
    while (!stack.isEmpty()) {
      sum += stack.pop();
    }
    System.out.println(sum); // Stack 합계 구하기
    
    Stack<Integer> stack2 = new Stack<>();
    stack2.push(1);
    stack2.push(2);
    stack2.push(3);

    sum = stack2.stream().mapToInt(Integer::intValue).sum();
    System.out.println(sum); // Stream을 이용한 Stack 합계 구하기

  }
}

자바에서 Stack의 합계를 구하려면 while을 이용해서 stack을 비워가며 합계를 구하는 방법과, Stream을 사용해서 합계를 구하는 방법이 있는데 차이점은 while과 pop을 사용할 경우 합계를 구한 후 stack은 모두 비워지게 되지만

Stream을 사용할 경우 Stack을 비우지 않고 합계를 구할 수 있다.

No Comments
0

Leave a Reply Cancel Reply

Introduction

My Codegate

Latest Posts

  • Google Search Console API 연동방법
  • 인텔리제이 Gradle Dependency 최신 버전 보는 방법
  • Wallet-Tracker 개발일지
  • Moralis API 자바로 호출방법
  • IntelliJ Commit 후 Push 따로 하는 방법

Categories

  • My Project (4)
  • Java (42)
  • Algorithm (161)
    • Java (152)
    • Algorithm Knowledge (3)
    • Algorithm site usage (6)
  • Vue.js (1)
  • Spring (4)
  • Docker (2)
  • IntelliJ (20)
  • Uncategorized (7)

Recent Comments

  • Codegate on Hello world!
  • A WordPress Commenter on Hello world!

© 2025 — mycodegate.com

Prev Next