Java 8のSpliterator、Collector、Streamを理解する 質問する

Java 8のSpliterator、Collector、Streamを理解する 質問する

理解に苦しんでいますStreamJava 8のインターフェース、特にSpliteratorそしてCollectorSpliteratorインターフェース。私の問題は、インターフェースをまだ理解できずCollector、その結果、Streamインターフェースがまだ私にとってややわかりにくいということです。

Spliteratorと とは正確には何ですかCollector? また、これらをどのように使用できますか? 独自のSpliteratorまたはCollector(おそらくStreamその過程で独自の ) を作成するつもりである場合、何をすべきで、何をすべきでないか?

私はウェブ上に散らばっているいくつかの例を読みましたが、ここにあるものはすべてまだ新しく、変更される可能性があるため、例とチュートリアルはまだ非常にまばらです。

ベストアンサー1

Spliteratorユーザーとして対処する必要はほとんどないでしょう。Collection自分で型を書いていて、また intending to optimize parallelized operations on them.

For what it's worth, a Spliterator is a way of operating over the elements of a collection in a way that it's easy to split off part of the collection, e.g. because you're parallelizing and want one thread to work on one part of the collection, one thread to work on another part, etc.

You should essentially never be saving values of type Stream to a variable, either. Stream is sort of like an Iterator, in that it's a one-time-use object that you'll almost always use in a fluent chain, as in the Javadoc example:

int sum = widgets.stream()
                  .filter(w -> w.getColor() == RED)
                  .mapToInt(w -> w.getWeight())
                  .sum();

Collector is the most generalized, abstract possible version of a "reduce" operation a la map/reduce; in particular, it needs to support parallelization and finalization steps. Examples of Collectors include:

  • summing, e.g. Collectors.reducing(0, (x, y) -> x + y)
  • StringBuilder appending, e.g. Collector.of(StringBuilder::new, StringBuilder::append, StringBuilder::append, StringBuilder::toString)

おすすめ記事