Functional
Stream.toList: 変更できない List を返す
Stream.toList の結果は、内容が同じでも add を受け付けない List です。
SourceImmutableStreamLists.java
Java 21
package examples.stream;
import java.util.List;
public final class ImmutableStreamLists {
private ImmutableStreamLists() {}
public static List<String> copyOf(List<String> values) {
return values.stream().toList();
}
}TestImmutableStreamListsTest.java
Java 21
package examples.stream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.List;
import org.junit.jupiter.api.Test;
class ImmutableStreamListsTest {
@Test
void StreamToListは入力と同じ内容のListを返す() {
assertEquals(List.of("A", "B"), ImmutableStreamLists.copyOf(List.of("A", "B")));
}
@Test
void StreamToListが返すListには要素を追加できない() {
var list = ImmutableStreamLists.copyOf(List.of("A"));
assertThrows(UnsupportedOperationException.class, () -> list.add("B"));
}
}01Assertion
このテストで確認できること
- toList はストリームの値を順序どおり返す
- 結果に add すると UnsupportedOperationException になる
Collectors.toList の可変性に依存せず、変更不可の結果を明示したいときに Stream.toList を使います。
OBSERVED RESULT
expected exception:
UnsupportedOperationException