JDK1.8の新機能(A):ストリーム

A.ストリームとは何ですか?

1.概要

JavaのAPI 8は、ストリームストリームと呼ばれる新しい抽象概念が追加されますが、宣言的な方法でデータを処理することができます。

このスタイル要素は、パイプライン送信の処理フローストリームの集まりとして見られることを、そしてこのようなフィルタリング、ソート、重合として、ノード導管で処理することができます。

パイプライン処理におけるエレメンタリストリームは、中間動作の後、及び最終的に前の処理動作の最終結果を得ました。

このようなものを何かの簡単な説明:

II。例を与えるには?

文字列のコレクションが用意されました、私たちは、長さが2以上の内部の文字列の集合をフィルタリングする必要があります。

public static void main( String[] args ) {
    List<String> strings = Arrays.asList("ab", "", "bc", "cd", "abcd","", "jkl");
    List<String> stringList = new ArrayList<>();
    for (String str : strings){
        //如果长度大于2
        if (str.length() >= 2){
            //将字符串添加至新集合
            stringList.add(str);
        }
    }
    strings = stringList;
}

あなたはまったく同じ効果を達成するために、ストリームを使用する場合:

public static void main( String[] args ) {
    List<String> strings = Arrays.asList("ab", "", "bc", "cd", "abcd","", "jkl");
    //通过stream操作集合
    strings = strings.stream()
        //去掉长度小于2的字符串
        .filter(s -> s.length() >= 2)
        //转回集合
        .collect(Collectors.toList());
}

目に見える、使用streamAPIは簡単に、より効率的に、より簡潔、より読みやすいコードを書くことができます

III。どのようにストリームを使用するには?

2つのステップで簡単に言えば、:ストリームを生成、操作の流れ

ストリームを生成1.

作成する必要の流れは、地図をサポートしていない、などのjava.util.Collectionサブクラス、リストやセットなどのデータソースを指定します

1.1コレクションストリーム()またはparallelStream()インターフェースメソッド

//将Set或List集合直接转换为stream对象
List<Person> personList = new ArrayList<>();
Set<Person> set = new HashSet<>();

Stream<Person> personStream1 = personList.stream();//生成串行流
Stream<Person> personStream2 = set.parallelStream();//生成并行流

1.2 Stream.of()、Arrays.stream、Stream.empty()方法

String[] strArr = {"a","a","a","a","a","a"};

//Stream.empty()
Stream<Integer> integerStream = Stream.empty();

//Stream.of() (方法内部调用的还是Arrays.stream)
Stream<String> stringStream = Stream.of(strArr);

//Arrays.stream
Stream<String> stringStream2 = Arrays.stream(strArr);

1.3 Stream.concat()メソッド

//已有的对象
Stream<Integer> integerStream = Stream.empty();
Stream<String> stringStream = Stream.of(strArr);
Stream<String> stringStream2 = Arrays.stream(strArr);

//合并两个流
Stream conStream1 = Stream.concat(stringStream,integerStream);
Stream conStream2 = Stream.concat(stringStream,stringStream2);

1.4静的Files.lines(パス)

File file = new File("D://test.txt");
Stream<String> lines = Files.lines(file);

2.操作の流れ

操作の2種類の操作の中間体または最終操作にストリーム操作は計算の特定の種類の最終的な結果を返し、中間ストリーム自体に対して動作戻り、他の中間動作の背後についていくことができ

//接下来的示例代码基于此集合
List<String> strings = Arrays.asList("ab", "", "bc", "cd", "abcd","", "jkl");

2.1フィルタ(述語:結果が偽のフィルタリングの要素であります

//去掉长度小于2的字符串
strings = strings.stream()
    .filter(s -> s.length() >= 2)
    //返回集合
    .collect(Collectors.toList());

System.out.println(strings);

//打印strings
[ab, bc, cd, abcd, jkl]

(FUN)2.2マップ:値変換素子は、方法又は直接ラムダ式を挙げることができます

strings = strings.stream()
    //为每个字符串加上“???”
    .map(s -> s += "???")
    //返回集合
    .collect(Collectors.toList());

System.out.println(strings);

//打印strings
[ab???, ???, bc???, cd???, abcd???, ???, jkl???]

2.3限界(N):最初のn個の要素予約

strings = strings.stream()
    //保留前3个
    .limit(3)
    //返回集合
    .collect(Collectors.toList());

System.out.println(strings);

//打印strings
[ab, , bc]

2.4スキップ(N):最初のn個の要素をスキップ

strings = strings.stream()
    //跳过前2个
    .skip(2)
    //返回集合
    .collect(Collectors.toList());

System.out.println(strings);

//打印strings
[bc, cd, abcd, , jkl]

2.5異なる():重複を排除

strings = strings.stream()
    //过滤重复元素
    .distinct()
    //返回集合
    .collect(Collectors.toList());

System.out.println(strings);

//打印strings(过滤掉了一个空字符串)
[ab, , bc, cd, abcd, jkl]

2.6ソート():同等の並び替え要素

strings = strings.stream()
    //按字符串长度排序
    .sorted(
        //比较字符串长度
        Comparator.comparing(s -> s.length())
    )
    //返回集合
    .collect(Collectors.toList());

System.out.println(strings);

//打印strings(过滤掉了一个空字符串)
[, , ab, bc, cd, jkl, abcd]

2.7 PEEK(楽しい):一定のフローが、実行するために楽しいの各要素を渡します、それはデバッグに使用することができます

strings = strings.stream()
    //为字符串增加“???”
    .peek(s -> s += "???")
    //返回集合
    .collect(Collectors.toList());

System.out.println(strings);

//打印strings,和map对比,实际并没有改变集合
[ab, , bc, cd, abcd, , jkl]

2.8 flatMap(FUN):要素が流れ、通常、変換素子等の素子を平滑フローである場合

//将具有多重嵌套结构的集合扁平化

//获取一个两重集合
List<String> strings = Arrays.asList("ab", "", "bc", "cd", "abcd","", "jkl");
List<String> strings2 = Arrays.asList("asd", "", "bzxasdc", "cddsdsd", "adsdsg","", "jvcbl");
List<List<String>> lists = new ArrayList<>();
lists.add(strings);
lists.add(strings2);

//获取将两重集合压成一层
List<String> stringList = lists.stream()
    //将两重集合的子元素,即集合strings和strings2转成流再平摊
    .flatMap(Collection::stream)
    //返回集合
    .collect(Collectors.toList());

System.out.println(stringList);

//打印stringList
[ab, , bc, cd, abcd, , jkl, asd, , bzxasdc, cddsdsd, adsdsg, , jvcbl]

2.9 anyMatch(fun)は、allMatch(楽しい):分析流は最終[動作]の要素と一致

//allMatch
Boolean isAllMatch = strings.stream()
    //判断元素中是否有匹配“ab”的字符串,返回true或fals
    //判断元素中的字符串是否都与“ab”匹配,返回true或fals
    .allMatch(str -> str.equals("ab"));

System.out.println(isMatch);

//anyMatch
Boolean isAnyMatch = strings.stream()
    //判断元素中是否有匹配“ab”的字符串,返回true或fals
    .anyMatch(str -> str.equals("ab"));

System.out.println("isAnyMatch:" + isAnyMatch);
System.out.println("isAllMatch:" + isAllMatch);

//打印结果
isAnyMatch:true
isAllMatch:false

2.10のforEach(FUN):各データストリームの反復[最終動作]

strings.stream()
    //遍历每一个元素
    .forEach(s -> System.out.print(s + "; "));

)(2.11収集:] [最終的な演算の結果セットを返します

strings = strings.stream()
    //返回集合
    .collect(Collectors.toList());

IV。IntSummaryStatisticsを使用してデータを処理

1. IntSummaryStatistics类

ストリーム内嵌IntSummaryStatisticsタイプは、統計情報(例えば、カウント、最小値、最大値、合計値、平均*)状態オブジェクトを収集するために使用java8。

このクラスは、長い道のりです。

public class IntSummaryStatistics implements IntConsumer {
    private long count;
    private long sum;
    private int min = Integer.MAX_VALUE;
    private int max = Integer.MIN_VALUE;
    
    public IntSummaryStatistics() { }

    @Override
    public void accept(int value) {
        ++count;
        sum += value;
        min = Math.min(min, value);
        max = Math.max(max, value);
    }

    public void combine(IntSummaryStatistics other) {
        count += other.count;
        sum += other.sum;
        min = Math.min(min, other.min);
        max = Math.max(max, other.max);
    }

    public final long getCount() {
        return count;
    }


    public final long getSum() {
        return sum;
    }

    public final int getMin() {
        return min;
    }

    public final int getMax() {
        return max;
    }

    public final double getAverage() {
        return getCount() > 0 ? (double) getSum() / getCount() : 0.0d;
    }

    @Override
    public String toString() {
        return String.format(
            "%s{count=%d, sum=%d, min=%d, average=%f, max=%d}",
            this.getClass().getSimpleName(),
            getCount(),
            getSum(),
            getMin(),
            getAverage(),
            getMax());
    }
}

2.

いくつかの方法があるの内側に、このクラスを理解することは非常に簡単です:

取得の2.1総数:同様にgetCount()、

2.2アクセス:getSum()、

)getMin(:2.3の最小値を求めます

2.4のGet最大:getMax()で、

2.5平均取得:getAverage()

例としては、次のとおりです:

public static void main( String[] args ) {
    List<Integer> integerList = Arrays.asList(3, 4, 22, 31, 75, 32, 54);

    IntSummaryStatistics sta = integerList
        .stream()
        //将元素映射为对应的数据类型(int,double,long)
        .mapToInt(i -> i)
        //转换为summaryStatistics类
        .summaryStatistics();

    System.out.println("总共有 : "+ sta.getCount());
    System.out.println("列表中最大的数 : " + sta.getMax());
    System.out.println("列表中最小的数 : " + sta.getMin());
    System.out.println("所有数之和 : " + sta.getSum());
    System.out.println("平均数 : " + sta.getAverage());
}

//打印结果
总共有 : 7
列表中最大的数 : 75
列表中最小的数 : 3
所有数之和 : 221
平均数 : 31.571428571428573

おすすめ

転載: www.cnblogs.com/Createsequence/p/11967561.html