文章

java8包装类支持流操作

本文介绍Java8中包装类支持流操作的原因及具体实现方式。解释了包装类为何需要支持流操作,并列举了多种功能接口如ToLongFunction、ToIntFunction等。此外,还详细介绍了IntStream接口的方法及使用案例。

java8包装类支持流操作

文章信息

  • 原文链接:https://jiayq.blog.csdn.net/article/details/89004490
  • 发布时间:2019-04-08 19:11:11
  • 阅读量:454
  • 分类:Java8专栏收录该内容, 订阅专栏
  • 标签:#包装类对基本类型的支持, #源码解读, #如何使用jdk封装的基本类型的流操作, #Java8快速处理数据, #基本类型与包装类

摘要

文章浏览阅读454次。本文介绍Java8中包装类支持流操作的原因及具体实现方式。解释了包装类为何需要支持流操作,并列举了多种功能接口如ToLongFunction、ToIntFunction等。此外,还详细介绍了IntStream接口的方法及使用案例。


java8包装类支持流操作

  • 1.为什么包装类需要对流进行支持
  • 2.有哪些包装类
    • 2.1ToLongFunction:Long->long
      • 2.2ToIntFunction:Integer->int
      • 2.3ToDoubleFunction:Double->double
      • 2.4ToDoubleBiFunction:doSome:Double->double
      • 2.5ToIntBiFunction:doSome:Double->double
      • 2.6ToLongBiFunction:doSome:Long->long
      • 2.7IntFunction:int -> Int
      • 2.8LongFunction:long -> Long
      • 2.9DoubleFunction:double -> Double
  • 3.对应的流操作
    • 3.1IntStream
  • 4.如何使用

1.为什么包装类需要对流进行支持

首先应该知道,包装类存在的一个重要的原因就是基本类型与包装类映射可以把基本类型当做普通类处理,而且在存储上基本类型又能大大的节省内存。
所以包装类需要对流进行支持。
比如

1
List<int> list = new ArrayList<>();

其实list是List类型的
因为int 类型存储需要4个字节
而Integer类型需要16个字节
所以,如果有10W个长度的int需要40W的字节
而Integer需要160W字节
所以为了节省内存,需要包装类对流进行支持。
但是是支持所有的基本类型还是支持部分的基本类型,Java8中对整形、长整型和双浮点型进行了处理:

2.有哪些包装类

2.1ToLongFunction:Long->long

1
2
3
4
5
package java.util.function;
@FunctionalInterface
public interface ToLongFunction<T> {
    long applyAsLong(T value);
}

2.2ToIntFunction:Integer->int

1
2
3
4
5
package java.util.function;
@FunctionalInterface
public interface ToIntFunction<T> {
    int applyAsInt(T value);
}

2.3ToDoubleFunction:Double->double

1
2
3
4
5
package java.util.function;
@FunctionalInterface
public interface ToDoubleFunction<T> {
    double applyAsDouble(T value);
}

2.4ToDoubleBiFunction:doSome:Double->double

1
2
3
4
5
package java.util.function;
@FunctionalInterface
public interface ToDoubleBiFunction<T, U> {
    double applyAsDouble(T t, U u);
}

2.5ToIntBiFunction:doSome:Double->double

1
2
3
4
5
package java.util.function;
@FunctionalInterface
public interface ToIntBiFunction<T, U> {
    int applyAsInt(T t, U u);
}

2.6ToLongBiFunction:doSome:Long->long

1
2
3
4
5
package java.util.function;
@FunctionalInterface
public interface ToLongBiFunction<T, U> {
    long applyAsLong(T t, U u);
}

2.7IntFunction:int -> Int

1
2
3
4
5
package java.util.function;
@FunctionalInterface
public interface IntFunction<R> {
    R apply(int value);
}

2.8LongFunction:long -> Long

1
2
3
4
5
package java.util.function;
@FunctionalInterface
public interface LongFunction<R> {
    R apply(long value);
}

2.9DoubleFunction:double -> Double

1
2
3
4
5
package java.util.function;
@FunctionalInterface
public interface DoubleFunction<R> {
    R apply(double value);
}

3.对应的流操作

3.1IntStream

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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
package java.util.stream;

import java.util.Arrays;
import java.util.IntSummaryStatistics;
import java.util.Objects;
import java.util.OptionalDouble;
import java.util.OptionalInt;
import java.util.PrimitiveIterator;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.function.IntBinaryOperator;
import java.util.function.IntConsumer;
import java.util.function.IntFunction;
import java.util.function.IntPredicate;
import java.util.function.IntSupplier;
import java.util.function.IntToDoubleFunction;
import java.util.function.IntToLongFunction;
import java.util.function.IntUnaryOperator;
import java.util.function.ObjIntConsumer;
import java.util.function.Supplier;
public interface IntStream extends BaseStream<Integer, IntStream> {
    IntStream filter(IntPredicate predicate);
    IntStream map(IntUnaryOperator mapper);
    <U> Stream<U> mapToObj(IntFunction<? extends U> mapper);
    LongStream mapToLong(IntToLongFunction mapper);
    DoubleStream mapToDouble(IntToDoubleFunction mapper);
    IntStream flatMap(IntFunction<? extends IntStream> mapper);
    IntStream distinct();
    IntStream sorted();
    IntStream peek(IntConsumer action);
    IntStream limit(long maxSize);
    IntStream skip(long n);
    void forEach(IntConsumer action);
    void forEachOrdered(IntConsumer action);
    int[] toArray();
    int reduce(int identity, IntBinaryOperator op);
    OptionalInt reduce(IntBinaryOperator op);
    <R> R collect(Supplier<R> supplier,
                  ObjIntConsumer<R> accumulator,
                  BiConsumer<R, R> combiner);
    int sum();
    OptionalInt min();
    OptionalInt max();
    long count();
    OptionalDouble average();
    IntSummaryStatistics summaryStatistics();
    boolean anyMatch(IntPredicate predicate);
    boolean allMatch(IntPredicate predicate);
    boolean noneMatch(IntPredicate predicate);
    OptionalInt findFirst();
    OptionalInt findAny();
    LongStream asLongStream();
    DoubleStream asDoubleStream();
    Stream<Integer> boxed();

    @Override
    IntStream sequential();

    @Override
    IntStream parallel();

    @Override
    PrimitiveIterator.OfInt iterator();

    @Override
    Spliterator.OfInt spliterator();
    // Static factories
    public static Builder builder() {
        return new Streams.IntStreamBuilderImpl();
    }
    public static IntStream empty() {
        return StreamSupport.intStream(Spliterators.emptyIntSpliterator(), false);
    }
    public static IntStream of(int t) {
        return StreamSupport.intStream(new Streams.IntStreamBuilderImpl(t), false);
    }
    public static IntStream of(int... values) {
        return Arrays.stream(values);
    }
    public static IntStream iterate(final int seed, final IntUnaryOperator f) {
        Objects.requireNonNull(f);
        final PrimitiveIterator.OfInt iterator = new PrimitiveIterator.OfInt() {
            int t = seed;

            @Override
            public boolean hasNext() {
                return true;
            }

            @Override
            public int nextInt() {
                int v = t;
                t = f.applyAsInt(t);
                return v;
            }
        };
        return StreamSupport.intStream(Spliterators.spliteratorUnknownSize(
                iterator,
                Spliterator.ORDERED | Spliterator.IMMUTABLE | Spliterator.NONNULL), false);
    }
    public static IntStream generate(IntSupplier s) {
        Objects.requireNonNull(s);
        return StreamSupport.intStream(
                new StreamSpliterators.InfiniteSupplyingSpliterator.OfInt(Long.MAX_VALUE, s), false);
    }
    public static IntStream range(int startInclusive, int endExclusive) {
        if (startInclusive >= endExclusive) {
            return empty();
        } else {
            return StreamSupport.intStream(
                    new Streams.RangeIntSpliterator(startInclusive, endExclusive, false), false);
        }
    }
    public static IntStream rangeClosed(int startInclusive, int endInclusive) {
        if (startInclusive > endInclusive) {
            return empty();
        } else {
            return StreamSupport.intStream(
                    new Streams.RangeIntSpliterator(startInclusive, endInclusive, true), false);
        }
    }
    public static IntStream concat(IntStream a, IntStream b) {
        Objects.requireNonNull(a);
        Objects.requireNonNull(b);

        Spliterator.OfInt split = new Streams.ConcatSpliterator.OfInt(
                a.spliterator(), b.spliterator());
        IntStream stream = StreamSupport.intStream(split, a.isParallel() || b.isParallel());
        return stream.onClose(Streams.composedClose(a, b));
    }
    public interface Builder extends IntConsumer {
        @Override
        void accept(int t);
        default Builder add(int t) {
            accept(t);
            return this;
        }
        IntStream build();
    }
}

4.如何使用

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
	@Test
	public void method7(){
		LongSummaryStatistics statistics = Main.getUsers()
				.stream()
				.mapToLong(u -> {
					System.out.print(u);
					return u.getId();
				}).summaryStatistics();
		System.out.println("max:"+statistics.getMax());
		System.out.println("min:"+statistics.getMin());
		System.out.println("ave:"+statistics.getAverage());
		System.out.println("sum:"+statistics.getSum());
	}



{id=58,name=name:0.2689475499558849}
{id=51,name=name:0.6716262160499563}
{id=38,name=name:0.06574632673216096}
{id=70,name=name:0.6792261605337495}
{id=33,name=name:0.2516699155393817}
{id=84,name=name:0.6028574395729949}
{id=76,name=name:0.23834435845470736}
{id=30,name=name:0.4791369843257146}
{id=5,name=name:0.30710665597599773}
{id=77,name=name:0.4131467144257531}max:84
min:5
ave:52.2
sum:522
本文由作者按照 CC BY 4.0 进行授权