LoginSignup
3
5

More than 5 years have passed since last update.

初心者向けJava8ラムダ演習1

Last updated at Posted at 2017-08-23

【注意】
解答はこの記事にコメントせずに、自分の記事として投稿して、この記事にリンクを張るようにしてください。
一旦作った記事なので、演習問題は後日追加されることがあります。

演習1 ループの置き換え

次のコードに示されるループの部分をStream APIを用いたコードに変換せよ。
なお解答のコードは問題のクラス名にSolをサフィックスとして追加し、さらに[+α]の課題について、問題に示されるクラスが同じものである場合はAをSolの前に追加し、ASolを追加して保存せよ。

演習1-1

forループをStream APIのforEachメソッドで置き換えよ。
[+α] コードをより短くなるように改良せよ。

Practice1.java
import java.util.List;
import java.util.ArrayList;

public class Practice1 {
  static public void main(String[] args) {
    List<String> helloWorld = new ArrayList<String>(3);
    helloWorld.add("Hello");
    helloWorld.add(" ");
    helloWorld.add("World");
    helloWorld.add("!");
    for (int i = 0; i < helloWorld.size(); i++) {
      System.out.print(helloWorld.get(i));
    }
  }
}

演習1-2

次のwhileループをStringクラスのcharsメソッドで取得できるIntStreamを使用して置き換えよ。
(※ IntStreamとして取得されることに注意)

Practice2.java
public class Practice2 {
  static public void main(String[] args) {
    String sourceText = "this is an test script to read.";
    int i = 0;
    char c = sourceText.charAt(i);
    while (c != '.') {
      if (c > 'm') {
        System.out.print(Character.toUpperCase(c));
      } else {
        System.out.print(c);
      }
      c = sourceText.charAt(++i);
    }
    System.out.print(".\n");
  }
}

[+α] 以下のようにループの中で計算されている値を条件としている場合はどうなるか。

Practice2A.java
public class Practice2A {
  static private final int MAX = 1024;

  static public void main(String[] args) {
    String sourceText = "this is an test script to read.";
    int i = 0;
    char c = sourceText.charAt(i);
    int sum = c;
    while (sum < MAX) {
      if (c > 'm') {
        System.out.print(Character.toUpperCase(c));
      } else {
        System.out.print(c);
      }
      c = sourceText.charAt(++i);
      sum += c;
    }
    System.out.print("\n");
    if (sum >= MAX) {
      System.out.println("script stopped for MAX size limitation.");
    }
  }
}
3
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
5