|
| 1 | +package com.baeldung.java.conversion; |
| 2 | + |
| 3 | +import java.util.Arrays; |
| 4 | +import java.util.Iterator; |
| 5 | +import java.util.List; |
| 6 | +import java.util.stream.Collectors; |
| 7 | +import java.util.stream.Stream; |
| 8 | +import java.util.stream.StreamSupport; |
| 9 | + |
| 10 | +import org.junit.Assert; |
| 11 | +import org.junit.Test; |
| 12 | + |
| 13 | +public class IterableStreamConversionTest { |
| 14 | + |
| 15 | + @Test |
| 16 | + public void givenIterable_whenConvertedToStream_thenTrue() { |
| 17 | + String[] names = { "Testing", "Iterable", "conversion", "to", "Stream" }; |
| 18 | + StreamIterable<String> iterable = new StreamIterable<>(names); |
| 19 | + Assert.assertTrue(StreamSupport.stream(iterable.spliterator(), false) instanceof Stream<?>); |
| 20 | + } |
| 21 | + |
| 22 | + @Test |
| 23 | + public void whenConvertedToList_thenCorrect() { |
| 24 | + String[] names = { "Testing", "Iterable", "conversion", "to", "Stream" }; |
| 25 | + StreamIterable<String> iterable = new StreamIterable<>(names); |
| 26 | + Stream<String> convertedStream = StreamSupport.stream(iterable.spliterator(), false); |
| 27 | + Assert.assertTrue(convertedStream.map(String::toUpperCase) |
| 28 | + .collect(Collectors.toList()) instanceof List<?>); |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | +class StreamIterable<T> implements Iterable<T> { |
| 33 | + private List<T> list; |
| 34 | + |
| 35 | + public StreamIterable(T[] array) { |
| 36 | + this.list = Arrays.asList(array); |
| 37 | + } |
| 38 | + |
| 39 | + @Override |
| 40 | + public Iterator<T> iterator() { |
| 41 | + return list.iterator(); |
| 42 | + } |
| 43 | + |
| 44 | +} |
0 commit comments