logo

Java 8-Stream

Java stellt in Java 8 ein neues Zusatzpaket namens java.util.stream bereit. Dieses Paket besteht aus Klassen, Schnittstellen und Enumerationen, um funktionale Operationen an den Elementen zu ermöglichen. Sie können Stream verwenden, indem Sie das Paket java.util.stream importieren.


Stream bietet folgende Funktionen:

  • Stream speichert keine Elemente. Es überträgt einfach Elemente aus einer Quelle, etwa einer Datenstruktur, einem Array oder einem I/O-Kanal, über eine Pipeline von Rechenoperationen.
  • Stream ist funktionaler Natur. An einem Stream ausgeführte Vorgänge ändern nicht seine Quelle. Wenn Sie beispielsweise einen aus einer Sammlung erhaltenen Stream filtern, wird ein neuer Stream ohne die gefilterten Elemente erstellt, anstatt Elemente aus der Quellsammlung zu entfernen.
  • Stream ist faul und wertet Code nur bei Bedarf aus.
  • Die Elemente eines Streams werden während der Lebensdauer eines Streams nur einmal besucht. Wie bei einem Iterator muss ein neuer Stream generiert werden, um dieselben Elemente der Quelle erneut aufzurufen.

Sie können Stream zum Filtern, Sammeln, Drucken und Konvertieren von einer Datenstruktur in eine andere usw. verwenden. In den folgenden Beispielen haben wir verschiedene Operationen mithilfe von Stream angewendet.

Methoden der Java-Stream-Schnittstelle

Methoden Beschreibung
boolean allMatch(Prädikatprädikat) Es gibt alle Elemente dieses Streams zurück, die mit dem bereitgestellten Prädikat übereinstimmen. Wenn der Stream leer ist, wird true zurückgegeben und das Prädikat wird nicht ausgewertet.
boolean anyMatch(Prädikatprädikat) Es gibt jedes Element dieses Streams zurück, das mit dem bereitgestellten Prädikat übereinstimmt. Wenn der Stream leer ist, wird „false“ zurückgegeben und das Prädikat wird nicht ausgewertet.
statischer Stream.Builder builder() Es gibt einen Builder für einen Stream zurück.
R sammeln (Kollektor-Kollektor) Es führt mithilfe eines Collectors eine veränderliche Reduktionsoperation für die Elemente dieses Streams durch. Ein Collector kapselt die Funktionen, die als Argumente für die Sammlung verwendet werden (Lieferant, BiConsumer, BiConsumer), und ermöglicht so die Wiederverwendung von Sammlungsstrategien und die Zusammensetzung von Sammlungsvorgängen, z. B. Gruppierung oder Partitionierung auf mehreren Ebenen.
R sammeln (Lieferant Lieferant, BiConsumer-Akkumulator, BiConsumer-Kombinator) Es führt eine veränderliche Reduktionsoperation für die Elemente dieses Streams durch. Bei einer veränderlichen Reduzierung handelt es sich um eine veränderliche Reduzierung, bei der der reduzierte Wert ein veränderlicher Ergebniscontainer ist, beispielsweise eine ArrayList, und Elemente durch Aktualisieren des Status des Ergebnisses und nicht durch Ersetzen des Ergebnisses eingebunden werden.
static Stream concat(Stream a, Stream b) Es erstellt einen träge verketteten Stream, dessen Elemente alle Elemente des ersten Streams sind, gefolgt von allen Elementen des zweiten Streams. Der resultierende Stream ist geordnet, wenn beide Eingabeströme geordnet sind, und parallel, wenn einer der Eingabeströme parallel ist. Wenn der resultierende Stream geschlossen wird, werden die Close-Handler für beide Eingabestreams aufgerufen.
lange Zählung() Es gibt die Anzahl der Elemente in diesem Stream zurück. Dies ist ein Sonderfall einer Reduktion.
Streamen Sie eindeutig() Es gibt einen Stream zurück, der aus den unterschiedlichen Elementen (gemäß Object.equals(Object)) dieses Streams besteht.
statischer Stream empty() Es gibt einen leeren sequentiellen Stream zurück.
Stream-Filter (Prädikatprädikat) Es gibt einen Stream zurück, der aus den Elementen dieses Streams besteht, die mit dem angegebenen Prädikat übereinstimmen.
Optional findAny() Es gibt ein Optional zurück, das ein Element des Streams beschreibt, oder ein leeres Optional, wenn der Stream leer ist.
Optional findFirst() Es gibt ein Optional zurück, das das erste Element dieses Streams beschreibt, oder ein leeres Optional, wenn der Stream leer ist. Wenn der Stream keine Begegnungsreihenfolge hat, kann jedes Element zurückgegeben werden.
Stream flatMap(FunktionMapper) Es gibt einen Stream zurück, der aus den Ergebnissen des Ersetzens jedes Elements dieses Streams durch den Inhalt eines zugeordneten Streams besteht, der durch Anwenden der bereitgestellten Zuordnungsfunktion auf jedes Element erstellt wurde. Jeder zugeordnete Stream wird geschlossen, nachdem sein Inhalt in diesem Stream platziert wurde. (Wenn ein zugeordneter Stream null ist, wird stattdessen ein leerer Stream verwendet.)
DoubleStream flatMapToDouble(Funktionsmapper) Es gibt einen DoubleStream zurück, der aus den Ergebnissen des Ersetzens jedes Elements dieses Streams durch den Inhalt eines zugeordneten Streams besteht, der durch Anwenden der bereitgestellten Zuordnungsfunktion auf jedes Element erstellt wurde. Jeder zugeordnete Stream wird geschlossen, nachdem sein Inhalt in diesem Stream platziert wurde. (Wenn ein zugeordneter Stream null ist, wird stattdessen ein leerer Stream verwendet.)
IntStream flatMapToInt(Funktionsmapper) Es gibt einen IntStream zurück, der aus den Ergebnissen des Ersetzens jedes Elements dieses Streams durch den Inhalt eines zugeordneten Streams besteht, der durch Anwenden der bereitgestellten Zuordnungsfunktion auf jedes Element erstellt wurde. Jeder zugeordnete Stream wird geschlossen, nachdem sein Inhalt in diesem Stream platziert wurde. (Wenn ein zugeordneter Stream null ist, wird stattdessen ein leerer Stream verwendet.)
LongStream flatMapToLong(Funktionsmapper) Es gibt einen LongStream zurück, der aus den Ergebnissen des Ersetzens jedes Elements dieses Streams durch den Inhalt eines zugeordneten Streams besteht, der durch Anwenden der bereitgestellten Zuordnungsfunktion auf jedes Element erstellt wurde. Jeder zugeordnete Stream wird geschlossen, nachdem sein Inhalt in diesem Stream platziert wurde. (Wenn ein zugeordneter Stream null ist, wird stattdessen ein leerer Stream verwendet.)
void forEach(Verbraucheraktion) Es führt eine Aktion für jedes Element dieses Streams aus.
void forEachOrdered(Verbraucheraktion) Es führt eine Aktion für jedes Element dieses Streams in der Begegnungsreihenfolge des Streams aus, wenn der Stream eine definierte Begegnungsreihenfolge hat.
statischer Stream generieren (Lieferanten) Es gibt einen unendlichen sequentiellen ungeordneten Stream zurück, in dem jedes Element vom bereitgestellten Lieferanten generiert wird. Dies eignet sich zum Erzeugen konstanter Streams, Streams zufälliger Elemente usw.
static Stream iterate(T Seed,UnaryOperator f) Es gibt einen unendlichen sequentiell geordneten Stream zurück, der durch iterative Anwendung einer Funktion f auf einen anfänglichen Element-Seed erzeugt wird und einen Stream erzeugt, der aus Seed, f(Seed), f(f(Seed)) usw. besteht.
Stream-Limit (long maxSize) Es gibt einen Stream zurück, der aus den Elementen dieses Streams besteht und so gekürzt ist, dass er nicht länger als maxSize ist.
Stream-Map (Funktions-Mapper) Es gibt einen Stream zurück, der aus den Ergebnissen der Anwendung der angegebenen Funktion auf die Elemente dieses Streams besteht.
DoubleStream mapToDouble(ToDoubleFunction-Mapper) Es gibt einen DoubleStream zurück, der aus den Ergebnissen der Anwendung der angegebenen Funktion auf die Elemente dieses Streams besteht.
IntStream mapToInt(ToIntFunction Mapper) Es gibt einen IntStream zurück, der aus den Ergebnissen der Anwendung der angegebenen Funktion auf die Elemente dieses Streams besteht.
LongStream mapToLong(ToLongFunction Mapper) Es gibt einen LongStream zurück, der aus den Ergebnissen der Anwendung der angegebenen Funktion auf die Elemente dieses Streams besteht.
Optional max (Komparator Komparator) Es gibt das maximale Element dieses Streams gemäß dem bereitgestellten Komparator zurück. Dies ist ein Sonderfall einer Reduktion.
Optional min(Komparator Komparator) Es gibt das minimale Element dieses Streams gemäß dem bereitgestellten Komparator zurück. Dies ist ein Sonderfall einer Reduktion.
boolean noneMatch(Prädikatprädikat) Es werden Elemente dieses Streams zurückgegeben, die mit dem bereitgestellten Prädikat übereinstimmen. Wenn der Stream leer ist, wird true zurückgegeben und das Prädikat wird nicht ausgewertet.
@SafeVarargs statischer Stream von (T... Werten) Es gibt einen sequentiell geordneten Stream zurück, dessen Elemente die angegebenen Werte sind.
statischer Strom von (T t) Es gibt einen sequentiellen Stream zurück, der ein einzelnes Element enthält.
Stream-Peek (Verbraucheraktion) Es gibt einen Stream zurück, der aus den Elementen dieses Streams besteht, und führt zusätzlich die bereitgestellte Aktion für jedes Element aus, wenn Elemente aus dem resultierenden Stream verbraucht werden.
Optionale Reduzierung (BinaryOperator-Akkumulator) Es führt mithilfe einer assoziativen Akkumulationsfunktion eine Reduzierung der Elemente dieses Streams durch und gibt gegebenenfalls eine optionale Beschreibung des reduzierten Werts zurück.
T Reduce(T Identität, BinaryOperator Akkumulator) Es führt eine Reduzierung der Elemente dieses Streams durch, indem es den bereitgestellten Identitätswert und eine assoziative Akkumulationsfunktion verwendet, und gibt den reduzierten Wert zurück.
U Reduzieren (U-Identität, BiFunction-Akkumulator, BinaryOperator-Kombinierer) Es führt eine Reduzierung der Elemente dieses Streams durch und nutzt dabei die bereitgestellten Identitäts-, Akkumulations- und Kombinationsfunktionen.
Stream überspringen (langes n) Es gibt einen Stream zurück, der aus den verbleibenden Elementen dieses Streams besteht, nachdem die ersten n Elemente des Streams verworfen wurden. Wenn dieser Stream weniger als n Elemente enthält, wird ein leerer Stream zurückgegeben.
Stream sortiert() Es gibt einen Stream zurück, der aus den Elementen dieses Streams besteht, sortiert nach natürlicher Reihenfolge. Wenn die Elemente dieses Streams nicht vergleichbar sind, wird möglicherweise eine java.lang.ClassCastException ausgelöst, wenn die Terminaloperation ausgeführt wird.
Stream sortiert (Komparator Komparator) Es gibt einen Stream zurück, der aus den Elementen dieses Streams besteht, sortiert nach dem bereitgestellten Komparator.
Object[] toArray() Es gibt ein Array zurück, das die Elemente dieses Streams enthält.
A[] toArray(IntFunction-Generator) Es gibt ein Array zurück, das die Elemente dieses Streams enthält, und verwendet die bereitgestellte Generatorfunktion, um das zurückgegebene Array sowie alle zusätzlichen Arrays zuzuweisen, die möglicherweise für eine partitionierte Ausführung oder zur Größenänderung erforderlich sind.

Java-Beispiel: Sammlung filtern, ohne Stream zu verwenden

Im folgenden Beispiel filtern wir Daten, ohne Stream zu verwenden. Diesen Ansatz haben wir verwendet, bevor das Stream-Paket veröffentlicht wurde.

Java-Zeichenfolge anhängen
 import java.util.*; class Product{ int id; String name; float price; public Product(int id, String name, float price) { this.id = id; this.name = name; this.price = price; } } public class JavaStreamExample { public static void main(String[] args) { List productsList = new ArrayList(); //Adding Products productsList.add(new Product(1,&apos;HP Laptop&apos;,25000f)); productsList.add(new Product(2,&apos;Dell Laptop&apos;,30000f)); productsList.add(new Product(3,&apos;Lenevo Laptop&apos;,28000f)); productsList.add(new Product(4,&apos;Sony Laptop&apos;,28000f)); productsList.add(new Product(5,&apos;Apple Laptop&apos;,90000f)); List productPriceList = new ArrayList(); for(Product product: productsList){ // filtering data of list if(product.price<30000){ productpricelist.add(product.price); adding price to a productpricelist } system.out.println(productpricelist); displaying data < pre> <p> <strong>Output:</strong> </p> <pre> [25000.0, 28000.0, 28000.0] </pre> <hr> <h3>Java Stream Example: Filtering Collection by using Stream</h3> <p>Here, we are filtering data by using stream. You can see that code is optimized and maintained. Stream provides fast execution.</p> <pre> import java.util.*; import java.util.stream.Collectors; class Product{ int id; String name; float price; public Product(int id, String name, float price) { this.id = id; this.name = name; this.price = price; } } public class JavaStreamExample { public static void main(String[] args) { List productsList = new ArrayList(); //Adding Products productsList.add(new Product(1,&apos;HP Laptop&apos;,25000f)); productsList.add(new Product(2,&apos;Dell Laptop&apos;,30000f)); productsList.add(new Product(3,&apos;Lenevo Laptop&apos;,28000f)); productsList.add(new Product(4,&apos;Sony Laptop&apos;,28000f)); productsList.add(new Product(5,&apos;Apple Laptop&apos;,90000f)); List productPriceList2 =productsList.stream() .filter(p -&gt; p.price &gt; 30000)// filtering data .map(p-&gt;p.price) // fetching price .collect(Collectors.toList()); // collecting as list System.out.println(productPriceList2); } } </pre> <p> <strong>Output:</strong> </p> <pre> [90000.0] </pre> <hr> <h3>Java Stream Iterating Example</h3> <p>You can use stream to iterate any number of times. Stream provides predefined methods to deal with the logic you implement. In the following example, we are iterating, filtering and passed a limit to fix the iteration.</p> <pre> import java.util.stream.*; public class JavaStreamExample { public static void main(String[] args){ Stream.iterate(1, element-&gt;element+1) .filter(element-&gt;element%5==0) .limit(5) .forEach(System.out::println); } } </pre> <p> <strong>Output:</strong> </p> <pre> 5 10 15 20 25 </pre> <hr> <h3>Java Stream Example: Filtering and Iterating Collection</h3> <p>In the following example, we are using filter() method. Here, you can see code is optimized and very concise.</p> <pre> import java.util.*; class Product{ int id; String name; float price; public Product(int id, String name, float price) { this.id = id; this.name = name; this.price = price; } } public class JavaStreamExample { public static void main(String[] args) { List productsList = new ArrayList(); //Adding Products productsList.add(new Product(1,&apos;HP Laptop&apos;,25000f)); productsList.add(new Product(2,&apos;Dell Laptop&apos;,30000f)); productsList.add(new Product(3,&apos;Lenevo Laptop&apos;,28000f)); productsList.add(new Product(4,&apos;Sony Laptop&apos;,28000f)); productsList.add(new Product(5,&apos;Apple Laptop&apos;,90000f)); // This is more compact approach for filtering data productsList.stream() .filter(product -&gt; product.price == 30000) .forEach(product -&gt; System.out.println(product.name)); } } </pre> <p> <strong>Output:</strong> </p> <pre> Dell Laptop </pre> <hr> <h3>Java Stream Example : reduce() Method in Collection</h3> <p>This method takes a sequence of input elements and combines them into a single summary result by repeated operation. For example, finding the sum of numbers, or accumulating elements into a list. </p> <p>In the following example, we are using reduce() method, which is used to sum of all the product prices.</p> <pre> import java.util.*; class Product{ int id; String name; float price; public Product(int id, String name, float price) { this.id = id; this.name = name; this.price = price; } } public class JavaStreamExample { public static void main(String[] args) { List productsList = new ArrayList(); //Adding Products productsList.add(new Product(1,&apos;HP Laptop&apos;,25000f)); productsList.add(new Product(2,&apos;Dell Laptop&apos;,30000f)); productsList.add(new Product(3,&apos;Lenevo Laptop&apos;,28000f)); productsList.add(new Product(4,&apos;Sony Laptop&apos;,28000f)); productsList.add(new Product(5,&apos;Apple Laptop&apos;,90000f)); // This is more compact approach for filtering data Float totalPrice = productsList.stream() .map(product-&gt;product.price) .reduce(0.0f,(sum, price)-&gt;sum+price); // accumulating price System.out.println(totalPrice); // More precise code float totalPrice2 = productsList.stream() .map(product-&gt;product.price) .reduce(0.0f,Float::sum); // accumulating price, by referring method of Float class System.out.println(totalPrice2); } } </pre> <p> <strong>Output:</strong> </p> <pre> 201000.0 201000.0 </pre> <hr> <h3>Java Stream Example: Sum by using Collectors Methods</h3> <p>We can also use collectors to compute sum of numeric values. In the following example, we are using Collectors class and it?s specified methods to compute sum of all the product prices.</p> <pre> import java.util.*; import java.util.stream.Collectors; class Product{ int id; String name; float price; public Product(int id, String name, float price) { this.id = id; this.name = name; this.price = price; } } public class JavaStreamExample { public static void main(String[] args) { List productsList = new ArrayList(); //Adding Products productsList.add(new Product(1,&apos;HP Laptop&apos;,25000f)); productsList.add(new Product(2,&apos;Dell Laptop&apos;,30000f)); productsList.add(new Product(3,&apos;Lenevo Laptop&apos;,28000f)); productsList.add(new Product(4,&apos;Sony Laptop&apos;,28000f)); productsList.add(new Product(5,&apos;Apple Laptop&apos;,90000f)); // Using Collectors&apos;s method to sum the prices. double totalPrice3 = productsList.stream() .collect(Collectors.summingDouble(product-&gt;product.price)); System.out.println(totalPrice3); } } </pre> <p> <strong>Output:</strong> </p> <pre> 201000.0 </pre> <hr> <h3>Java Stream Example: Find Max and Min Product Price</h3> <p>Following example finds min and max product price by using stream. It provides convenient way to find values without using imperative approach.</p> <pre> import java.util.*; class Product{ int id; String name; float price; public Product(int id, String name, float price) { this.id = id; this.name = name; this.price = price; } } public class JavaStreamExample { public static void main(String[] args) { List productsList = new ArrayList(); //Adding Products productsList.add(new Product(1,&apos;HP Laptop&apos;,25000f)); productsList.add(new Product(2,&apos;Dell Laptop&apos;,30000f)); productsList.add(new Product(3,&apos;Lenevo Laptop&apos;,28000f)); productsList.add(new Product(4,&apos;Sony Laptop&apos;,28000f)); productsList.add(new Product(5,&apos;Apple Laptop&apos;,90000f)); // max() method to get max Product price Product productA = productsList.stream().max((product1, product2)-&gt;product1.price &gt; product2.price ? 1: -1).get(); System.out.println(productA.price); // min() method to get min Product price Product productB = productsList.stream().min((product1, product2)-&gt;product1.price &gt; product2.price ? 1: -1).get(); System.out.println(productB.price); } } </pre> <p> <strong>Output:</strong> </p> <pre> 90000.0 25000.0 </pre> <hr> <h3>Java Stream Example: count() Method in Collection</h3> <pre> import java.util.*; class Product{ int id; String name; float price; public Product(int id, String name, float price) { this.id = id; this.name = name; this.price = price; } } public class JavaStreamExample { public static void main(String[] args) { List productsList = new ArrayList(); //Adding Products productsList.add(new Product(1,&apos;HP Laptop&apos;,25000f)); productsList.add(new Product(2,&apos;Dell Laptop&apos;,30000f)); productsList.add(new Product(3,&apos;Lenevo Laptop&apos;,28000f)); productsList.add(new Product(4,&apos;Sony Laptop&apos;,28000f)); productsList.add(new Product(5,&apos;Apple Laptop&apos;,90000f)); // count number of products based on the filter long count = productsList.stream() .filter(product-&gt;product.price<30000) .count(); system.out.println(count); } < pre> <p> <strong>Output:</strong> </p> <pre> 3 </pre> <p>stream allows you to collect your result in any various forms. You can get you result as set, list or map and can perform manipulation on the elements.</p> <hr> <h3>Java Stream Example : Convert List into Set</h3> <pre> import java.util.*; import java.util.stream.Collectors; class Product{ int id; String name; float price; public Product(int id, String name, float price) { this.id = id; this.name = name; this.price = price; } } public class JavaStreamExample { public static void main(String[] args) { List productsList = new ArrayList(); //Adding Products productsList.add(new Product(1,&apos;HP Laptop&apos;,25000f)); productsList.add(new Product(2,&apos;Dell Laptop&apos;,30000f)); productsList.add(new Product(3,&apos;Lenevo Laptop&apos;,28000f)); productsList.add(new Product(4,&apos;Sony Laptop&apos;,28000f)); productsList.add(new Product(5,&apos;Apple Laptop&apos;,90000f)); // Converting product List into Set Set productPriceList = productsList.stream() .filter(product-&gt;product.price product.price) .collect(Collectors.toSet()); // collect it as Set(remove duplicate elements) System.out.println(productPriceList); } } </pre> <p> <strong>Output:</strong> </p> <pre> [25000.0, 28000.0] </pre> <hr> <h3>Java Stream Example : Convert List into Map</h3> <pre> import java.util.*; import java.util.stream.Collectors; class Product{ int id; String name; float price; public Product(int id, String name, float price) { this.id = id; this.name = name; this.price = price; } } public class JavaStreamExample { public static void main(String[] args) { List productsList = new ArrayList(); //Adding Products productsList.add(new Product(1,&apos;HP Laptop&apos;,25000f)); productsList.add(new Product(2,&apos;Dell Laptop&apos;,30000f)); productsList.add(new Product(3,&apos;Lenevo Laptop&apos;,28000f)); productsList.add(new Product(4,&apos;Sony Laptop&apos;,28000f)); productsList.add(new Product(5,&apos;Apple Laptop&apos;,90000f)); // Converting Product List into a Map Map productPriceMap = productsList.stream() .collect(Collectors.toMap(p-&gt;p.id, p-&gt;p.name)); System.out.println(productPriceMap); } } </pre> <p> <strong>Output:</strong> </p> <pre> {1=HP Laptop, 2=Dell Laptop, 3=Lenevo Laptop, 4=Sony Laptop, 5=Apple Laptop} </pre> <hr> <h3>Method Reference in stream</h3> <pre> import java.util.*; import java.util.stream.Collectors; class Product{ int id; String name; float price; public Product(int id, String name, float price) { this.id = id; this.name = name; this.price = price; } public int getId() { return id; } public String getName() { return name; } public float getPrice() { return price; } } public class JavaStreamExample { public static void main(String[] args) { List productsList = new ArrayList(); //Adding Products productsList.add(new Product(1,&apos;HP Laptop&apos;,25000f)); productsList.add(new Product(2,&apos;Dell Laptop&apos;,30000f)); productsList.add(new Product(3,&apos;Lenevo Laptop&apos;,28000f)); productsList.add(new Product(4,&apos;Sony Laptop&apos;,28000f)); productsList.add(new Product(5,&apos;Apple Laptop&apos;,90000f)); List productPriceList = productsList.stream() .filter(p -&gt; p.price &gt; 30000) // filtering data .map(Product::getPrice) // fetching price by referring getPrice method .collect(Collectors.toList()); // collecting as list System.out.println(productPriceList); } } </pre> <p> <strong>Output:</strong> </p> <pre> [90000.0] </pre> <hr></30000)></pre></30000){>

Java-Stream-Beispiel: Sammlung mithilfe von Stream filtern

Hier filtern wir Daten mithilfe von Stream. Sie können sehen, dass der Code optimiert und gepflegt wird. Stream sorgt für eine schnelle Ausführung.

 import java.util.*; import java.util.stream.Collectors; class Product{ int id; String name; float price; public Product(int id, String name, float price) { this.id = id; this.name = name; this.price = price; } } public class JavaStreamExample { public static void main(String[] args) { List productsList = new ArrayList(); //Adding Products productsList.add(new Product(1,&apos;HP Laptop&apos;,25000f)); productsList.add(new Product(2,&apos;Dell Laptop&apos;,30000f)); productsList.add(new Product(3,&apos;Lenevo Laptop&apos;,28000f)); productsList.add(new Product(4,&apos;Sony Laptop&apos;,28000f)); productsList.add(new Product(5,&apos;Apple Laptop&apos;,90000f)); List productPriceList2 =productsList.stream() .filter(p -&gt; p.price &gt; 30000)// filtering data .map(p-&gt;p.price) // fetching price .collect(Collectors.toList()); // collecting as list System.out.println(productPriceList2); } } 

Ausgabe:

 [90000.0] 

Beispiel für eine Java-Stream-Iteration

Sie können Stream verwenden, um beliebig oft zu iterieren. Stream bietet vordefinierte Methoden für den Umgang mit der von Ihnen implementierten Logik. Im folgenden Beispiel führen wir eine Iteration durch, filtern und übergeben einen Grenzwert, um die Iteration zu korrigieren.

 import java.util.stream.*; public class JavaStreamExample { public static void main(String[] args){ Stream.iterate(1, element-&gt;element+1) .filter(element-&gt;element%5==0) .limit(5) .forEach(System.out::println); } } 

Ausgabe:

 5 10 15 20 25 

Beispiel für einen Java-Stream: Filtern und Iterieren der Sammlung

Im folgenden Beispiel verwenden wir die Methode filter(). Hier können Sie sehen, dass der Code optimiert und sehr prägnant ist.

 import java.util.*; class Product{ int id; String name; float price; public Product(int id, String name, float price) { this.id = id; this.name = name; this.price = price; } } public class JavaStreamExample { public static void main(String[] args) { List productsList = new ArrayList(); //Adding Products productsList.add(new Product(1,&apos;HP Laptop&apos;,25000f)); productsList.add(new Product(2,&apos;Dell Laptop&apos;,30000f)); productsList.add(new Product(3,&apos;Lenevo Laptop&apos;,28000f)); productsList.add(new Product(4,&apos;Sony Laptop&apos;,28000f)); productsList.add(new Product(5,&apos;Apple Laptop&apos;,90000f)); // This is more compact approach for filtering data productsList.stream() .filter(product -&gt; product.price == 30000) .forEach(product -&gt; System.out.println(product.name)); } } 

Ausgabe:

 Dell Laptop 

Beispiel für einen Java-Stream: Methode „reduction()“ in der Sammlung

Diese Methode nimmt eine Folge von Eingabeelementen und kombiniert sie durch wiederholten Vorgang zu einem einzigen zusammenfassenden Ergebnis. Zum Beispiel das Ermitteln der Summe von Zahlen oder das Sammeln von Elementen in einer Liste.

Im folgenden Beispiel verwenden wir die Methode Reduce(), mit der alle Produktpreise summiert werden.

 import java.util.*; class Product{ int id; String name; float price; public Product(int id, String name, float price) { this.id = id; this.name = name; this.price = price; } } public class JavaStreamExample { public static void main(String[] args) { List productsList = new ArrayList(); //Adding Products productsList.add(new Product(1,&apos;HP Laptop&apos;,25000f)); productsList.add(new Product(2,&apos;Dell Laptop&apos;,30000f)); productsList.add(new Product(3,&apos;Lenevo Laptop&apos;,28000f)); productsList.add(new Product(4,&apos;Sony Laptop&apos;,28000f)); productsList.add(new Product(5,&apos;Apple Laptop&apos;,90000f)); // This is more compact approach for filtering data Float totalPrice = productsList.stream() .map(product-&gt;product.price) .reduce(0.0f,(sum, price)-&gt;sum+price); // accumulating price System.out.println(totalPrice); // More precise code float totalPrice2 = productsList.stream() .map(product-&gt;product.price) .reduce(0.0f,Float::sum); // accumulating price, by referring method of Float class System.out.println(totalPrice2); } } 

Ausgabe:

 201000.0 201000.0 

Java-Stream-Beispiel: Summe mithilfe von Collectors-Methoden

Wir können auch Kollektoren verwenden, um die Summe numerischer Werte zu berechnen. Im folgenden Beispiel verwenden wir die Collectors-Klasse und ihre angegebenen Methoden, um die Summe aller Produktpreise zu berechnen.

 import java.util.*; import java.util.stream.Collectors; class Product{ int id; String name; float price; public Product(int id, String name, float price) { this.id = id; this.name = name; this.price = price; } } public class JavaStreamExample { public static void main(String[] args) { List productsList = new ArrayList(); //Adding Products productsList.add(new Product(1,&apos;HP Laptop&apos;,25000f)); productsList.add(new Product(2,&apos;Dell Laptop&apos;,30000f)); productsList.add(new Product(3,&apos;Lenevo Laptop&apos;,28000f)); productsList.add(new Product(4,&apos;Sony Laptop&apos;,28000f)); productsList.add(new Product(5,&apos;Apple Laptop&apos;,90000f)); // Using Collectors&apos;s method to sum the prices. double totalPrice3 = productsList.stream() .collect(Collectors.summingDouble(product-&gt;product.price)); System.out.println(totalPrice3); } } 

Ausgabe:

 201000.0 

Beispiel für einen Java-Stream: Ermitteln Sie den maximalen und minimalen Produktpreis

Das folgende Beispiel ermittelt den minimalen und maximalen Produktpreis mithilfe von Stream. Es bietet eine bequeme Möglichkeit, Werte zu finden, ohne einen imperativen Ansatz zu verwenden.

 import java.util.*; class Product{ int id; String name; float price; public Product(int id, String name, float price) { this.id = id; this.name = name; this.price = price; } } public class JavaStreamExample { public static void main(String[] args) { List productsList = new ArrayList(); //Adding Products productsList.add(new Product(1,&apos;HP Laptop&apos;,25000f)); productsList.add(new Product(2,&apos;Dell Laptop&apos;,30000f)); productsList.add(new Product(3,&apos;Lenevo Laptop&apos;,28000f)); productsList.add(new Product(4,&apos;Sony Laptop&apos;,28000f)); productsList.add(new Product(5,&apos;Apple Laptop&apos;,90000f)); // max() method to get max Product price Product productA = productsList.stream().max((product1, product2)-&gt;product1.price &gt; product2.price ? 1: -1).get(); System.out.println(productA.price); // min() method to get min Product price Product productB = productsList.stream().min((product1, product2)-&gt;product1.price &gt; product2.price ? 1: -1).get(); System.out.println(productB.price); } } 

Ausgabe:

 90000.0 25000.0 

Java-Stream-Beispiel: count()-Methode in der Sammlung

 import java.util.*; class Product{ int id; String name; float price; public Product(int id, String name, float price) { this.id = id; this.name = name; this.price = price; } } public class JavaStreamExample { public static void main(String[] args) { List productsList = new ArrayList(); //Adding Products productsList.add(new Product(1,&apos;HP Laptop&apos;,25000f)); productsList.add(new Product(2,&apos;Dell Laptop&apos;,30000f)); productsList.add(new Product(3,&apos;Lenevo Laptop&apos;,28000f)); productsList.add(new Product(4,&apos;Sony Laptop&apos;,28000f)); productsList.add(new Product(5,&apos;Apple Laptop&apos;,90000f)); // count number of products based on the filter long count = productsList.stream() .filter(product-&gt;product.price<30000) .count(); system.out.println(count); } < pre> <p> <strong>Output:</strong> </p> <pre> 3 </pre> <p>stream allows you to collect your result in any various forms. You can get you result as set, list or map and can perform manipulation on the elements.</p> <hr> <h3>Java Stream Example : Convert List into Set</h3> <pre> import java.util.*; import java.util.stream.Collectors; class Product{ int id; String name; float price; public Product(int id, String name, float price) { this.id = id; this.name = name; this.price = price; } } public class JavaStreamExample { public static void main(String[] args) { List productsList = new ArrayList(); //Adding Products productsList.add(new Product(1,&apos;HP Laptop&apos;,25000f)); productsList.add(new Product(2,&apos;Dell Laptop&apos;,30000f)); productsList.add(new Product(3,&apos;Lenevo Laptop&apos;,28000f)); productsList.add(new Product(4,&apos;Sony Laptop&apos;,28000f)); productsList.add(new Product(5,&apos;Apple Laptop&apos;,90000f)); // Converting product List into Set Set productPriceList = productsList.stream() .filter(product-&gt;product.price product.price) .collect(Collectors.toSet()); // collect it as Set(remove duplicate elements) System.out.println(productPriceList); } } </pre> <p> <strong>Output:</strong> </p> <pre> [25000.0, 28000.0] </pre> <hr> <h3>Java Stream Example : Convert List into Map</h3> <pre> import java.util.*; import java.util.stream.Collectors; class Product{ int id; String name; float price; public Product(int id, String name, float price) { this.id = id; this.name = name; this.price = price; } } public class JavaStreamExample { public static void main(String[] args) { List productsList = new ArrayList(); //Adding Products productsList.add(new Product(1,&apos;HP Laptop&apos;,25000f)); productsList.add(new Product(2,&apos;Dell Laptop&apos;,30000f)); productsList.add(new Product(3,&apos;Lenevo Laptop&apos;,28000f)); productsList.add(new Product(4,&apos;Sony Laptop&apos;,28000f)); productsList.add(new Product(5,&apos;Apple Laptop&apos;,90000f)); // Converting Product List into a Map Map productPriceMap = productsList.stream() .collect(Collectors.toMap(p-&gt;p.id, p-&gt;p.name)); System.out.println(productPriceMap); } } </pre> <p> <strong>Output:</strong> </p> <pre> {1=HP Laptop, 2=Dell Laptop, 3=Lenevo Laptop, 4=Sony Laptop, 5=Apple Laptop} </pre> <hr> <h3>Method Reference in stream</h3> <pre> import java.util.*; import java.util.stream.Collectors; class Product{ int id; String name; float price; public Product(int id, String name, float price) { this.id = id; this.name = name; this.price = price; } public int getId() { return id; } public String getName() { return name; } public float getPrice() { return price; } } public class JavaStreamExample { public static void main(String[] args) { List productsList = new ArrayList(); //Adding Products productsList.add(new Product(1,&apos;HP Laptop&apos;,25000f)); productsList.add(new Product(2,&apos;Dell Laptop&apos;,30000f)); productsList.add(new Product(3,&apos;Lenevo Laptop&apos;,28000f)); productsList.add(new Product(4,&apos;Sony Laptop&apos;,28000f)); productsList.add(new Product(5,&apos;Apple Laptop&apos;,90000f)); List productPriceList = productsList.stream() .filter(p -&gt; p.price &gt; 30000) // filtering data .map(Product::getPrice) // fetching price by referring getPrice method .collect(Collectors.toList()); // collecting as list System.out.println(productPriceList); } } </pre> <p> <strong>Output:</strong> </p> <pre> [90000.0] </pre> <hr></30000)>

Stream ermöglicht es Ihnen, Ihr Ergebnis in verschiedenen Formen zu sammeln. Sie können Ihr Ergebnis als Menge, Liste oder Karte erhalten und die Elemente bearbeiten.


Java-Stream-Beispiel: Liste in Set konvertieren

 import java.util.*; import java.util.stream.Collectors; class Product{ int id; String name; float price; public Product(int id, String name, float price) { this.id = id; this.name = name; this.price = price; } } public class JavaStreamExample { public static void main(String[] args) { List productsList = new ArrayList(); //Adding Products productsList.add(new Product(1,&apos;HP Laptop&apos;,25000f)); productsList.add(new Product(2,&apos;Dell Laptop&apos;,30000f)); productsList.add(new Product(3,&apos;Lenevo Laptop&apos;,28000f)); productsList.add(new Product(4,&apos;Sony Laptop&apos;,28000f)); productsList.add(new Product(5,&apos;Apple Laptop&apos;,90000f)); // Converting product List into Set Set productPriceList = productsList.stream() .filter(product-&gt;product.price product.price) .collect(Collectors.toSet()); // collect it as Set(remove duplicate elements) System.out.println(productPriceList); } } 

Ausgabe:

 [25000.0, 28000.0] 

Java-Stream-Beispiel: Liste in Karte konvertieren

 import java.util.*; import java.util.stream.Collectors; class Product{ int id; String name; float price; public Product(int id, String name, float price) { this.id = id; this.name = name; this.price = price; } } public class JavaStreamExample { public static void main(String[] args) { List productsList = new ArrayList(); //Adding Products productsList.add(new Product(1,&apos;HP Laptop&apos;,25000f)); productsList.add(new Product(2,&apos;Dell Laptop&apos;,30000f)); productsList.add(new Product(3,&apos;Lenevo Laptop&apos;,28000f)); productsList.add(new Product(4,&apos;Sony Laptop&apos;,28000f)); productsList.add(new Product(5,&apos;Apple Laptop&apos;,90000f)); // Converting Product List into a Map Map productPriceMap = productsList.stream() .collect(Collectors.toMap(p-&gt;p.id, p-&gt;p.name)); System.out.println(productPriceMap); } } 

Ausgabe:

 {1=HP Laptop, 2=Dell Laptop, 3=Lenevo Laptop, 4=Sony Laptop, 5=Apple Laptop} 

Methodenreferenz im Stream

 import java.util.*; import java.util.stream.Collectors; class Product{ int id; String name; float price; public Product(int id, String name, float price) { this.id = id; this.name = name; this.price = price; } public int getId() { return id; } public String getName() { return name; } public float getPrice() { return price; } } public class JavaStreamExample { public static void main(String[] args) { List productsList = new ArrayList(); //Adding Products productsList.add(new Product(1,&apos;HP Laptop&apos;,25000f)); productsList.add(new Product(2,&apos;Dell Laptop&apos;,30000f)); productsList.add(new Product(3,&apos;Lenevo Laptop&apos;,28000f)); productsList.add(new Product(4,&apos;Sony Laptop&apos;,28000f)); productsList.add(new Product(5,&apos;Apple Laptop&apos;,90000f)); List productPriceList = productsList.stream() .filter(p -&gt; p.price &gt; 30000) // filtering data .map(Product::getPrice) // fetching price by referring getPrice method .collect(Collectors.toList()); // collecting as list System.out.println(productPriceList); } } 

Ausgabe:

 [90000.0]