사실 더 간단히 풀이할 수도 있고 굳이 스트림을 쓰지 않아도 되는데 일부러 스트림을 쓰기 위해 코드를 작성한 것입니다. 스트림과 람다식을 응용하기 위한 연습으로 봐주세요.
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int N = scan.nextInt();
IntStream.rangeClosed(1, 9).forEach(j -> {
System.out.println(N + " * " + j + " = " + N*j);
});
scan.close();
}
}
range는 두 번째 파라미터를 범위를 포함하지 않고 rangeClosed()는 두번째 파라미터를 범위에 포함한다.
두 정수 A와 B를 입력받은 다음, A+B를 출력하는 프로그램을 작성하시오.
첫째 줄에 테스트 케이스의 개수 T가 주어진다.
각 테스트 케이스는 한 줄로 이루어져 있으며, 각 줄에 A와 B가 주어진다. (0 < A, B < 10)
각 테스트 케이스마다 A+B를 출력한다.

public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int t = scan.nextInt();
List<Integer> ab = new ArrayList<>();
IntStream.range(0, t).forEach(j -> {
int a = Integer.parseInt(scan.next());
int b = Integer.parseInt(scan.next());
ab.add(a+b);
});
ab.stream().forEach(i -> System.out.println(i));
scan.close();
}
}
n이 주어졌을 때, 1부터 n까지 합을 구하는 프로그램을 작성하시오.

public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int t = scan.nextInt();
AtomicInteger sum = new AtomicInteger();
IntStream.rangeClosed(1, t).forEach(sum::addAndGet);
System.out.println(sum.get());
scan.close();
}
}
메소드 참조(Method Reference)
메소드 참조란 함수형 인터페이스를 람다식이 아닌 일반 메소드를 참조시켜 선언하는 방법이다. 일반 메소드를 참조하기 위해서는 다음의 3가지 조건을 만족해야 한다.
함수형 인터페이스의 매개변수 타입 = 메소드의 매개변수 타입
함수형 인터페이스의 매개변수 개수 = 메소드의 매개변수 개수
함수형 인터페이스의 반환형 = 메소드의 반환형
참조가능한 메소드는 일반 메소드, Static 메소드, 생성자가 있으며 클래스이름::메소드이름 으로 참조할 수 있다.
//기존의 람다식
IntStream.rangeClosed(1, t).forEach(j -> sum.addAndGet(j));
//메소드 참조로 변경
IntStream.rangeClosed(1, t).forEach(sum::addAndGet);
준원이는 저번 주에 살면서 처음으로 코스트코를 가 봤다. 정말 멋졌다. 그런데, 몇 개 담지도 않았는데 수상하게 높은 금액이 나오는 것이다! 준원이는 영수증을 보면서 정확하게 계산된 것이 맞는지 확인해보려 한다.
영수증에 적힌,
구매한 각 물건의 가격과 개수
구매한 물건들의 총 금액
을 보고, 구매한 물건의 가격과 개수로 계산한 총 금액이 영수증에 적힌 총 금액과 일치하는지 검사해보자.
첫째 줄에는 영수증에 적힌 총 금액
가 주어진다.
둘째 줄에는 영수증에 적힌 구매한 물건의 종류의 수
이 주어진다.
이후
개의 줄에는 각 물건의 가격 와 개수 가 공백을 사이에 두고 주어진다.

public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int total = scan.nextInt();
int kind = scan.nextInt();
AtomicInteger sum = new AtomicInteger();
IntStream.range(0, kind).forEach(j ->{
int price = Integer.parseInt(scan.next());
int cnt = Integer.parseInt(scan.next());
sum.addAndGet(price * cnt);
});
if(total == Integer.parseInt(String.valueOf(sum))) System.out.println("Yes");
else System.out.println("No");
}
}

public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
IntStream.rangeClosed(1, n).forEach(i ->{
IntStream.range(0, i).forEach(j ->
System.out.print("*"));
System.out.println();
});
}
}