This series of articles comes from the
original CSDN address:
https://blog.csdn.net/ryo1060732496/article/details/88806342
- The reason for the specialization is not the complexity of the stream, but the complexity caused by the boxing-that is, the efficiency difference between int and Integer.
- Build flow
Specialized style
Java 8 introduced three primitive type specialization stream interfaces to solve the complexity caused by boxing: IntStream, DoubleStream and LongStream, respectively specializing the elements in the stream into int, long and double, thereby avoiding the implicit boxing cost .
Each interface brings new methods for commonly used numerical reductions, such as sum of numerical streams to find the max of the largest element.
1. Mapping to a numeric stream (mapToInt)
// 按照之前的归约 reduce 来计算总和,它有一个暗含的装箱成本,每个 Integer 都必须拆箱成一个原始类型,再进行求和
int calories = Restaurant.menu.stream()
.map(Dish::getCalories)
.reduce(0, Integer::sum);
// 映射到数值流
calories = Restaurant.menu.stream()
.mapToInt(Dish::getCalories)
.sum();
System.out.println(calories);
2. Convert back to the object stream (boxed)
IntStream intStream = Restaurant.menu.stream().mapToInt(Dish::getCalories);
Stream<Integer> boxed = intStream.boxed();
3. The default value (OptionalInt)
If the stream is empty, sum defaults to 0; max, min return OptionalInt
OptionalInt max = Restaurant.menu.stream().mapToInt(Dish::getCalories).max();
int i = max.orElse(1);
// 800
System.out.println(i);
// OptionalInt[800]
System.out.println(max);
Value range
Java 8 introduced two static methods that can be used for IntStream and LongStream to help generate this range: range (not including the end value) and rangeClosed (including the end value)
IntStream evenNumbers = IntStream.rangeClosed(1, 100).filter(x -> x % 2 == 0);
System.out.println(evenNumbers.count());
Build flow
1. Create a stream by value (Stream.of())
Stream<String> stringStream = Stream.of("Java","Hello","World");
stringStream.map(String::toUpperCase).forEach(System.out::println);
2. Create an empty stream (Stream.empty())
Stream<?> emptyStream = Stream.empty();
3. Create a stream from an array (Arrays.stream())
int[] ints = {
2,4,6,7,8};
int sum = Arrays.stream(ints).sum();
System.out.println(sum);
4. Generate a stream from a file
Many static methods in java.nio.file.Files return a stream
long uniqueWords;
try(Files.lines(Paths.get(ClassLoader.getSystemResource("data.txt").toURI()), Charset.defaultCharset())) {
uniqueWords = lines.flatMap(line -> Arrays.stream(line.split(" ")))
.distinct()
.count();
System.out.println("uniqueWords:" + uniqueWords);
}catch (IOException e) {
e.fillInStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
}
5.
Streams generated by functions Stream API provides two static methods to generate streams from functions: Stream.iterate() and Stream.generate() These two operations can create so-called infinite streams: unlike streams created from fixed collections That has a fixed-size stream.
Generally, limit(n) should be used to limit this stream to avoid printing infinitely many values
Stream.iterate(0,n -> n+2).limit(10).forEach(System.out::println);
Stream.generate(Math::random).limit(5).forEach(System.out::println);