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