1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2017-08-23

演習問題の回答例です。

演習1-1 解答例

Practice1Sol.java
import java.util.List;
import java.util.ArrayList;

public class Practice1Sol {
  static public void main(String[] args) {
    List<String> helloWorld = new ArrayList<String>(3);
    helloWorld.add("Hello");
    helloWorld.add(" ");
    helloWorld.add("World");
    helloWorld.add("!");
    helloWorld.stream().forEach(s -> {
      System.out.print(s);
    });
  }
}

演習1-1[+α] 解答例

Practice1ASol.java
import java.util.stream.Stream;

public class Practice1ASol {
  static public void main(String[] args) {
    Stream.of("Hello", " ", "World", "!").forEach(System.out::print);
  }
}

演習1-2 解答例

Practice2Sol.java
public class Practice2Sol {
  static public void main(String[] args) {
    String sourceText = "this is an test script to read.";
    sourceText
      .chars()
      .limit(sourceText.indexOf('.'))
      .map(c -> c > 'm' ? Character.toUpperCase(c) : c)
      .forEach(c -> System.out.print((char) c));
    System.out.print(".\n");
  }
}

演習1-2[+α] 解答例

実行結果の表示に限れば、例えば以下のように置き換えることは出来るが、このコードは元のループの置き換えとはなっていない。

Practice2ASol.java
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;

public class Practice2ASol {
  static private final int MAX = 1024;

  static public void main(String[] args) {
    String sourceText = "this is an test script to read.";
    List<Integer> sumBox = new ArrayList<>(sourceText.length());
    sourceText
      .chars()
      .mapToObj(c->{
        sumBox.add(sumBox.size() == 0 ? c : c + sumBox.get(sumBox.size() - 1) );
        return new AbstractMap.SimpleEntry<>(sumBox.get( sumBox.size()-1),c);
      })
      .filter(ent->ent.getKey()<=MAX)
      .mapToInt(Entry::getValue)
      .map(c -> c > 'm' ? Character.toUpperCase(c) : c)
      .forEach(c -> System.out.print((char) c));
    System.out.print("\n");
    if (sumBox.get(sumBox.size() - 1) > MAX) {
      System.out.println("script stopped for MAX size limitation.");
    }
  }
}

このコードを実行したとき、sumBox.size()は終端では、sourceText.length()と一致している。
それは、課題の元のコードにおけるwhileループの停止条件になっても、停止していないことを示している。
すなわち、この置き換え後のコードは無駄な処理を行っており、ループをStreamAPIによって単純に置き換えることが出来ないケースがあることを示している。

1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?