「Java」StreamクラスのforEachメソットを使うサンプル
説明
void forEach(Consumer<? super T> action)
このストリームの各要素に対してアクションを実行します。
Javaコード
package com.arkgame.study;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
public class StreamDemo {
private static List<String> opLst = Arrays.asList("A01", "B02", "C03", "D04", "E05");
public static void main(String[] args) {
StringBuffer sb = new StringBuffer();
Stream<String> st = opLst.stream();
System.out.println("Stream.forEach結果:");
// このストリームの各要素に対してアクションを実行します。
st.forEach(s -> {
System.out.println(s);
sb.append(s);
});
System.out.println("StringBuffer結果\n:" + sb.toString());
}
}
package com.arkgame.study;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
public class StreamDemo {
private static List<String> opLst = Arrays.asList("A01", "B02", "C03", "D04", "E05");
public static void main(String[] args) {
StringBuffer sb = new StringBuffer();
Stream<String> st = opLst.stream();
System.out.println("Stream.forEach結果:");
// このストリームの各要素に対してアクションを実行します。
st.forEach(s -> {
System.out.println(s);
sb.append(s);
});
System.out.println("StringBuffer結果\n:" + sb.toString());
}
}
package com.arkgame.study; import java.util.Arrays; import java.util.List; import java.util.stream.Stream; public class StreamDemo { private static List<String> opLst = Arrays.asList("A01", "B02", "C03", "D04", "E05"); public static void main(String[] args) { StringBuffer sb = new StringBuffer(); Stream<String> st = opLst.stream(); System.out.println("Stream.forEach結果:"); // このストリームの各要素に対してアクションを実行します。 st.forEach(s -> { System.out.println(s); sb.append(s); }); System.out.println("StringBuffer結果\n:" + sb.toString()); } }
実行結果
Stream.forEach結果:
A01
B02
C03
D04
E05
StringBuffer結果
:A01B02C03D04E05