1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
| package cn.kevinq.article.stream;
import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; import java.util.stream.Collectors; import java.util.stream.DoubleStream; import java.util.stream.IntStream; import java.util.stream.LongStream; import java.util.stream.Stream;
public class SteamTest {
public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add("a"); list.add("b"); String[] array = new String[] {"a", "b", "c"};
Stream<String> emptyStream = Stream.empty(); Stream<String> listToStream = list.stream(); Stream<String> arrayToStream = Stream.of(array); Stream<String> arrayToStream2 = Stream.of("a", "b", "c"); Stream<String> arrayToStream3 = Arrays.stream(array, 1, 3); Stream<String> streamBuilder = Stream.<String>builder().add("a").add("b").add("c").build(); Stream<String> streamGenrated = Stream.<String>generate(() -> { Random random = new Random(); return "" + random.nextInt(100); }).limit(10); Stream<String> streamIterate = Stream.<String>iterate("a", e -> { return (char) (e.charAt(e.length()-1) + 1) + ""; }).limit(26); IntStream intStream = IntStream.rangeClosed(1, 10); LongStream longStream = LongStream.range(1, 5); Random random = new Random(); DoubleStream doubleStream = random.doubles(3); DoubleStream doubleStream2 = DoubleStream.iterate(1l, n -> n + 1l).limit(10); System.out.println(emptyStream.collect(Collectors.toList()));
System.out.println(arrayToStream.collect(Collectors.toList())); System.out.println(arrayToStream2.collect(Collectors.toList())); System.out.println(arrayToStream3.collect(Collectors.toList())); System.out.println(streamBuilder.collect(Collectors.toList())); System.out.println(streamGenrated.collect(Collectors.toList())); System.out.println(streamIterate.collect(Collectors.toList())); System.out.println(intStream.boxed().collect(Collectors.toList())); System.out.println(longStream.boxed().collect(Collectors.toList())); System.out.println(doubleStream.boxed().collect(Collectors.toList())); System.out.println(doubleStream2.boxed().collect(Collectors.toList()));
System.out.println(listToStream.findFirst().orel); }
static Stream<BigInteger> primes() { return Stream.iterate(BigInteger.ONE.add(BigInteger.ONE), BigInteger::nextProbablePrime); }
}
|