logo

Java 8 Stream

Java proporciona un nou paquet addicional a Java 8 anomenat java.util.stream. Aquest paquet consta de classes, interfícies i enumeració per permetre operacions d'estil funcional sobre els elements. Podeu utilitzar stream important el paquet java.util.stream.


Stream ofereix les funcions següents:

  • Stream no emmagatzema elements. Simplement transmet elements d'una font, com ara una estructura de dades, una matriu o un canal d'E/S, a través d'una canalització d'operacions computacionals.
  • El corrent és de naturalesa funcional. Les operacions realitzades en un flux no modifiquen la seva font. Per exemple, filtrar un flux obtingut d'una col·lecció produeix un nou flux sense els elements filtrats, en lloc d'eliminar elements de la col·lecció font.
  • El flux és mandros i avalua el codi només quan cal.
  • Els elements d'un rierol només es visiten una vegada durant la vida d'un rierol. Com un iterador, s'ha de generar un nou flux per revisar els mateixos elements de la font.

Podeu utilitzar stream per filtrar, recopilar, imprimir i convertir d'una estructura de dades a una altra, etc. En els exemples següents, hem aplicat diverses operacions amb l'ajuda de stream.

Mètodes d'interfície de flux de Java

Mètodes Descripció
booleà allMatch (predicat de predicat) Retorna tots els elements d'aquest flux que coincideixen amb el predicat proporcionat. Si el flux està buit, es retorna true i el predicat no s'avalua.
booleà anyMatch (predicat de predicat) Retorna qualsevol element d'aquest flux que coincideixi amb el predicat proporcionat. Si el flux està buit, es retorna false i el predicat no s'avalua.
estàtic Stream.Builder builder() Retorna un constructor per a un flux.
R collect (col·lector de col·leccionista) Realitza una operació de reducció mutable sobre els elements d'aquest flux mitjançant un Col·lector. Un Col·lector encapsula les funcions que s'utilitzen com a arguments per recopilar (Proveïdor, BiConsumer, BiConsumer), permetent la reutilització d'estratègies de recollida i la composició d'operacions de recollida, com ara l'agrupació o la partició de diversos nivells.
R collect (proveïdor del proveïdor, acumulador BiConsumer, combinador BiConsumer) Realitza una operació de reducció mutable sobre els elements d'aquest corrent. Una reducció mutable és aquella en què el valor reduït és un contenidor de resultats mutables, com ara una ArrayList, i els elements s'incorporen actualitzant l'estat del resultat en lloc de substituir el resultat.
Stream estàtic concat (Stream a, Stream b) Crea un corrent concatenat de manera mandrós els elements del qual són tots els elements del primer flux seguits de tots els elements del segon flux. El flux resultant s'ordena si tots dos fluxos d'entrada estan ordenats, i paral·lel si qualsevol dels fluxos d'entrada és paral·lel. Quan es tanca el flux resultant, s'invoquen els controladors de tancament dels dos fluxos d'entrada.
recompte llarg () Retorna el recompte d'elements d'aquest flux. Aquest és un cas especial de reducció.
Stream distinct() Retorna un flux que consta dels diferents elements (segons Object.equals(Object)) d'aquest flux.
Seqüència estàtica buida() Retorna un flux seqüencial buit.
Filtre de flux (predicat de predicat) Retorna un flux format pels elements d'aquest flux que coincideixen amb el predicat donat.
Opcional findAny() Retorna un Opcional que descriu algun element del flux, o un Opcional buit si el flux està buit.
Opcional findFirst() Retorna un Opcional que descriu el primer element d'aquest flux, o un Opcional buit si el flux està buit. Si el flux no té cap ordre de trobada, es pot retornar qualsevol element.
Transmet flatMap (Funciómapeador) Retorna un flux que consisteix en els resultats de la substitució de cada element d'aquest flux amb el contingut d'un flux assignat produït aplicant la funció de mapeig proporcionada a cada element. Cada flux assignat es tanca després que el seu contingut s'hagi col·locat en aquest flux. (Si un flux assignat és nul, s'utilitza un flux buit.)
DoubleStream flatMapToDouble (Mapeador de funcions) Retorna un DoubleStream que consisteix en els resultats de la substitució de cada element d'aquest flux amb el contingut d'un flux assignat produït aplicant la funció de mapeig proporcionada a cada element. Cada flux assignat es tanca després que el seu contingut s'hagi col·locat en aquest flux. (Si un flux assignat és nul, s'utilitza un flux buit.)
IntStream flatMapToInt (Mapeador de funcions) Retorna un IntStream que consisteix en els resultats de la substitució de cada element d'aquest flux amb el contingut d'un flux mapat produït aplicant la funció de mapeig proporcionada a cada element. Cada flux assignat es tanca després que el seu contingut s'hagi col·locat en aquest flux. (Si un flux assignat és nul, s'utilitza un flux buit.)
LongStream flatMapToLong (mapeador de funcions) Retorna un LongStream que consisteix en els resultats de la substitució de cada element d'aquest flux amb el contingut d'un flux mapat produït aplicant la funció de mapeig proporcionada a cada element. Cada flux assignat es tanca després que el seu contingut s'hagi col·locat en aquest flux. (Si un flux assignat és nul, s'utilitza un flux buit.)
void forEach (acció del consumidor) Realitza una acció per a cada element d'aquest flux.
void forEachOrdered (acció del consumidor) Realitza una acció per a cada element d'aquest flux, en l'ordre de trobada del flux si el flux té un ordre de trobada definit.
Generació de flux estàtic (proveïdors) Retorna un flux no ordenat seqüencial infinit on cada element és generat pel proveïdor proporcionat. Això és adequat per generar fluxos constants, fluxos d'elements aleatoris, etc.
Iteració de flux estàtic (llavor T, Operador Unary f) Retorna un Stream ordenat seqüencial infinit produït per l'aplicació iterativa d'una funció f a un element inicial llavor, produint un Stream format per llavor, f(llavor), f(f(llavor)), etc.
Límit de reproducció (mida màxima llarga) Retorna un flux format pels elements d'aquest flux, truncats perquè no tinguin una longitud superior a maxSize.
Mapa de flux (Mapeador de funcions) Retorna un flux que consta dels resultats d'aplicar la funció donada als elements d'aquest flux.
DoubleStream mapToDouble(ToDoubleFunction mapper) Retorna un DoubleStream que consisteix en els resultats d'aplicar la funció donada als elements d'aquest flux.
IntStream mapToInt(Mapeador de funcions ToInt) Retorna un IntStream que consta dels resultats d'aplicar la funció donada als elements d'aquest flux.
LongStream mapToLong (mapeador de funcions ToLong) Retorna un LongStream que consisteix en els resultats d'aplicar la funció donada als elements d'aquest flux.
Màx. opcional (comparador de comparació) Retorna l'element màxim d'aquest flux segons el comparador proporcionat. Aquest és un cas especial de reducció.
Min opcional (comparador comparador) Retorna l'element mínim d'aquest flux segons el comparador proporcionat. Aquest és un cas especial de reducció.
booleà noneMatch (predicat del predicat) Retorna elements d'aquest flux que coincideixen amb el predicat proporcionat. Si el flux està buit, es retorna true i el predicat no s'avalua.
@SafeVarargs Stream estàtic de (valors T...) Retorna un flux ordenat seqüencial els elements del qual són els valors especificats.
Corrent estàtic de (T t) Retorna un flux seqüencial que conté un sol element.
Vista de la reproducció (acció del consumidor) Retorna un flux format pels elements d'aquest flux, realitzant, a més, l'acció proporcionada a cada element a mesura que es consumeixen elements del flux resultant.
Reducció opcional (acumulador BinaryOperator) Realitza una reducció dels elements d'aquest corrent, utilitzant una funció d'acumulació associativa, i retorna un Opcional que descriu el valor reduït, si n'hi ha.
T redueix (identitat T, acumulador BinaryOperator) Realitza una reducció dels elements d'aquest flux, utilitzant el valor d'identitat proporcionat i una funció d'acumulació associativa, i retorna el valor reduït.
U redueix (identitat U, acumulador BiFunction, combinador BinaryOperator) Realitza una reducció dels elements d'aquest flux, utilitzant les funcions d'identitat, acumulació i combinació proporcionades.
Salt de reproducció (n llarg) Retorna un flux format pels elements restants d'aquest flux després de descartar els primers n elements del flux. Si aquest flux conté menys de n elements, es retornarà un flux buit.
Seqüència ordenada () Retorna un corrent format pels elements d'aquest corrent, ordenats segons l'ordre natural. Si els elements d'aquest flux no són comparables, es pot llançar una excepció java.lang.ClassCastException quan s'executa l'operació del terminal.
Seqüència ordenada (comparador de comparació) Retorna un flux format pels elements d'aquest flux, ordenats segons el comparador proporcionat.
Objecte[] toArray() Retorna una matriu que conté els elements d'aquest flux.
A[] toArray (generador d'IntFunction) Retorna una matriu que conté els elements d'aquest flux, utilitzant la funció generadora proporcionada per assignar la matriu retornada, així com qualsevol matriu addicional que es pugui requerir per a una execució particionada o per canviar la mida.

Exemple de Java: filtrar la col·lecció sense utilitzar Stream

A l'exemple següent, estem filtrant dades sense utilitzar el flux. Aquest enfocament s'utilitza abans que el paquet stream fos llançat.

el nom de
 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){>

Exemple de Java Stream: filtrar la col·lecció mitjançant Stream

Aquí, estem filtrant dades mitjançant stream. Podeu veure que el codi està optimitzat i mantingut. El flux proporciona una execució ràpida.

 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); } } 

Sortida:

 [90000.0] 

Exemple d'iteració del flux de Java

Podeu utilitzar el flux per repetir qualsevol nombre de vegades. Stream proporciona mètodes predefinits per fer front a la lògica que implementeu. A l'exemple següent, estem iterant, filtrant i superant un límit per corregir la iteració.

 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); } } 

Sortida:

 5 10 15 20 25 

Exemple de flux de Java: Col·lecció de filtrat i iteració

En l'exemple següent, estem utilitzant el mètode filter(). Aquí podeu veure que el codi està optimitzat i molt concís.

 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)); } } 

Sortida:

 Dell Laptop 

Java Stream Exemple: mètode reduce() a la col·lecció

Aquest mètode pren una seqüència d'elements d'entrada i els combina en un únic resultat de resum mitjançant operacions repetides. Per exemple, trobar la suma de nombres o acumular elements en una llista.

A l'exemple següent, estem utilitzant el mètode reduce(), que s'utilitza per sumar tots els preus dels productes.

 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); } } 

Sortida:

 201000.0 201000.0 

Exemple de flux de Java: suma mitjançant mètodes de col·leccionistes

També podem utilitzar col·leccionistes per calcular la suma de valors numèrics. En l'exemple següent, estem utilitzant la classe Col·leccionistes i els seus mètodes especificats per calcular la suma de tots els preus dels productes.

 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); } } 

Sortida:

 201000.0 

Exemple de flux de Java: cerca el preu màxim i mínim del producte

L'exemple següent cerca el preu mínim i màxim del producte mitjançant el flux. Proporciona una manera convenient de trobar valors sense utilitzar un enfocament imperatiu.

 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); } } 

Sortida:

 90000.0 25000.0 

Exemple de flux de Java: mètode count() a la col·lecció

 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 us permet recollir el vostre resultat en diferents formes. Podeu obtenir el vostre resultat com a conjunt, llista o mapa i podeu manipular els elements.


Exemple Java Stream: Converteix llista en conjunt

 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); } } 

Sortida:

 [25000.0, 28000.0] 

Exemple Java Stream: Converteix una llista en un mapa

 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); } } 

Sortida:

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

Referència del mètode al flux

 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); } } 

Sortida:

 [90000.0]