logo

Java 8 flusso

Java fornisce un nuovo pacchetto aggiuntivo in Java 8 chiamato java.util.stream. Questo pacchetto è costituito da classi, interfacce ed enumerazione per consentire operazioni in stile funzionale sugli elementi. È possibile utilizzare lo stream importando il pacchetto java.util.stream.


Il flusso offre le seguenti funzionalità:

  • Lo streaming non memorizza gli elementi. Trasporta semplicemente elementi da una fonte come una struttura dati, un array o un canale I/O, attraverso una pipeline di operazioni computazionali.
  • Il flusso è di natura funzionale. Le operazioni eseguite su un flusso non ne modificano l'origine. Ad esempio, filtrando uno Stream ottenuto da una raccolta si produce un nuovo Stream senza gli elementi filtrati, invece di rimuovere elementi dalla raccolta di origine.
  • Il flusso è lento e valuta il codice solo quando richiesto.
  • Gli elementi di un flusso vengono visitati solo una volta durante la vita di un flusso. Come un Iterator, è necessario generare un nuovo flusso per rivisitare gli stessi elementi della sorgente.

Puoi utilizzare stream per filtrare, raccogliere, stampare e convertire da una struttura dati a un'altra, ecc. Negli esempi seguenti, abbiamo applicato varie operazioni con l'aiuto di stream.

Metodi di interfaccia Java Stream

Metodi Descrizione
booleano allMatch(predicato predicato) Restituisce tutti gli elementi di questo flusso che corrispondono al predicato fornito. Se il flusso è vuoto, viene restituito true e il predicato non viene valutato.
booleano anyMatch(Predicato predicato) Restituisce qualsiasi elemento di questo flusso che corrisponde al predicato fornito. Se il flusso è vuoto, viene restituito false e il predicato non viene valutato.
generatore statico Stream.Builder() Restituisce un builder per uno Stream.
R raccogli(Collettore collezionista) Esegue un'operazione di riduzione mutabile sugli elementi di questo flusso utilizzando un Collector. Un agente di raccolta incapsula le funzioni utilizzate come argomenti per la raccolta (Fornitore, BiConsumer, BiConsumer), consentendo il riutilizzo delle strategie di raccolta e la composizione delle operazioni di raccolta come il raggruppamento o il partizionamento a più livelli.
R Collect (fornitore fornitore, accumulatore BiConsumer, combinatore BiConsumer) Esegue un'operazione di riduzione mutevole sugli elementi di questo flusso. Una riduzione modificabile è quella in cui il valore ridotto è un contenitore di risultati modificabili, ad esempio un ArrayList, e gli elementi vengono incorporati aggiornando lo stato del risultato anziché sostituendo il risultato.
flusso statico concat(flusso a, flusso b) Crea un flusso concatenato pigramente i cui elementi sono tutti gli elementi del primo flusso seguiti da tutti gli elementi del secondo flusso. Il flusso risultante è ordinato se entrambi i flussi di input sono ordinati e parallelo se uno dei flussi di input è parallelo. Quando il flusso risultante viene chiuso, vengono richiamati i gestori di chiusura per entrambi i flussi di input.
conteggio lungo() Restituisce il conteggio degli elementi in questo flusso. Questo è un caso particolare di riduzione.
Streaming distinto() Restituisce un flusso costituito dagli elementi distinti (secondo Object.equals(Object)) di questo flusso.
flusso statico vuoto() Restituisce uno stream sequenziale vuoto.
Filtro flusso (predicato predicato) Restituisce un flusso costituito dagli elementi di questo flusso che corrispondono al predicato specificato.
TrovaAny() facoltativo Restituisce un Opzionale che descrive qualche elemento dello stream, o un Opzionale vuoto se lo stream è vuoto.
FindFirst() facoltativo Restituisce un Opzionale che descrive il primo elemento di questo flusso o un Opzionale vuoto se il flusso è vuoto. Se il flusso non ha un ordine di incontro, è possibile restituire qualsiasi elemento.
Stream flatMap(Funzionemappatore) Restituisce un flusso costituito dai risultati della sostituzione di ciascun elemento di questo flusso con il contenuto di un flusso mappato prodotto applicando la funzione di mappatura fornita a ciascun elemento. Ogni flusso mappato viene chiuso dopo che i relativi contenuti sono stati inseriti in questo flusso. (Se un flusso mappato è nullo, viene invece utilizzato un flusso vuoto.)
DoubleStream flatMapToDouble(mappatore di funzioni) Restituisce un DoubleStream costituito dai risultati della sostituzione di ciascun elemento di questo flusso con il contenuto di un flusso mappato prodotto applicando la funzione di mappatura fornita a ciascun elemento. Ogni flusso mappato viene chiuso dopo che i suoi contenuti sono stati inseriti in questo flusso. (Se un flusso mappato è nullo, viene invece utilizzato un flusso vuoto.)
IntStream flatMapToInt(mappatore di funzioni) Restituisce un IntStream costituito dai risultati della sostituzione di ciascun elemento di questo flusso con il contenuto di un flusso mappato prodotto applicando la funzione di mappatura fornita a ciascun elemento. Ogni flusso mappato viene chiuso dopo che i relativi contenuti sono stati inseriti in questo flusso. (Se un flusso mappato è nullo, viene invece utilizzato un flusso vuoto.)
LongStream flatMapToLong(mappatore di funzioni) Restituisce un LongStream costituito dai risultati della sostituzione di ciascun elemento di questo flusso con il contenuto di un flusso mappato prodotto applicando la funzione di mappatura fornita a ciascun elemento. Ogni flusso mappato viene chiuso dopo che i relativi contenuti sono stati inseriti in questo flusso. (Se un flusso mappato è nullo, viene invece utilizzato un flusso vuoto.)
void forEach(Azione del consumatore) Esegue un'azione per ciascun elemento di questo flusso.
void forEachOrdered(Azione del consumatore) Esegue un'azione per ciascun elemento di questo flusso, nell'ordine di incontro del flusso se il flusso ha un ordine di incontro definito.
generazione di flussi statici (fornitori) Restituisce un flusso sequenziale non ordinato infinito in cui ogni elemento è generato dal fornitore fornito. Questo è adatto per generare flussi costanti, flussi di elementi casuali, ecc.
iterazione del flusso statico (seme T, UnaryOperator f) Restituisce un flusso ordinato sequenziale infinito prodotto dall'applicazione iterativa di una funzione f a un elemento iniziale seme, producendo un flusso costituito da seme, f(seme), f(f(seme)), ecc.
Limite di streaming (dimensione massima lunga) Restituisce un flusso costituito dagli elementi di questo flusso, troncato in modo che non sia più lungo di maxSize.
Mappa del flusso (mappatore di funzioni) Restituisce un flusso costituito dai risultati dell'applicazione della funzione data agli elementi di questo flusso.
DoubleStream mapToDouble(mapper ToDoubleFunction) Restituisce un DoubleStream costituito dai risultati dell'applicazione della funzione data agli elementi di questo flusso.
IntStream mapToInt(mapper ToIntFunction) Restituisce un IntStream costituito dai risultati dell'applicazione della funzione data agli elementi di questo flusso.
LongStream mapToLong(mappatore ToLongFunction) Restituisce un LongStream costituito dai risultati dell'applicazione della funzione data agli elementi di questo flusso.
Max opzionale (comparatore comparatore) Restituisce l'elemento massimo di questo flusso in base al comparatore fornito. Questo è un caso particolare di riduzione.
Min opzionale (comparatore comparatore) Restituisce l'elemento minimo di questo flusso in base al comparatore fornito. Questo è un caso particolare di riduzione.
booleano noneMatch(predicato predicato) Restituisce gli elementi di questo flusso che corrispondono al predicato fornito. Se il flusso è vuoto, viene restituito true e il predicato non viene valutato.
@SafeVarargs Flusso statico di (valori T...) Restituisce un flusso ordinato sequenziale i cui elementi sono i valori specificati.
Flusso statico di(T t) Restituisce uno Stream sequenziale contenente un singolo elemento.
Anteprima dello streaming (azione del consumatore) Restituisce un flusso costituito dagli elementi di questo flusso, eseguendo inoltre l'azione fornita su ciascun elemento man mano che gli elementi vengono consumati dal flusso risultante.
Riduzione opzionale (accumulatore BinaryOperator) Esegue una riduzione sugli elementi di questo flusso, utilizzando una funzione di accumulazione associativa, e restituisce un Opzionale che descrive il valore ridotto, se presente.
Riduzione T (identità T, accumulatore BinaryOperator) Esegue una riduzione sugli elementi di questo flusso, utilizzando il valore di identità fornito e una funzione di accumulazione associativa, e restituisce il valore ridotto.
Riduzione U (identità U, accumulatore BiFunction, combinatore BinaryOperator) Esegue una riduzione degli elementi di questo flusso, utilizzando le funzioni di identità, accumulazione e combinazione fornite.
Salta flusso (lungo n) Restituisce uno stream costituito dagli elementi rimanenti di questo stream dopo aver scartato i primi n elementi dello stream. Se questo flusso contiene meno di n elementi, verrà restituito un flusso vuoto.
Flusso ordinato() Restituisce un flusso costituito dagli elementi di questo flusso, ordinati secondo l'ordine naturale. Se gli elementi di questo flusso non sono comparabili, potrebbe essere generata un'eccezione java.lang.ClassCastException quando viene eseguita l'operazione del terminale.
Flusso ordinato (comparatore comparatore) Restituisce un flusso costituito dagli elementi di questo flusso, ordinati in base al comparatore fornito.
Oggetto[] aArray() Restituisce un array contenente gli elementi di questo flusso.
A[] toArray(generatore di funzioni Int) Restituisce un array contenente gli elementi di questo flusso, utilizzando la funzione generatrice fornita per allocare l'array restituito, nonché eventuali array aggiuntivi che potrebbero essere necessari per un'esecuzione partizionata o per il ridimensionamento.

Esempio Java: filtraggio della raccolta senza utilizzare Stream

Nell'esempio seguente, stiamo filtrando i dati senza utilizzare stream. Questo approccio veniva utilizzato prima del rilascio del pacchetto stream.

leggere il file Excel in Java
 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){>

Esempio di Java Stream: filtraggio della raccolta utilizzando Stream

Qui stiamo filtrando i dati utilizzando stream. Puoi vedere che il codice è ottimizzato e mantenuto. Il flusso fornisce un'esecuzione rapida.

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

Produzione:

 [90000.0] 

Esempio di iterazione del flusso Java

È possibile utilizzare lo stream per ripetere un numero qualsiasi di volte. Stream fornisce metodi predefiniti per gestire la logica implementata. Nell'esempio seguente, stiamo iterando, filtrando e superando un limite per correggere l'iterazione.

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

Produzione:

 5 10 15 20 25 

Esempio di Java Stream: raccolta di filtri e iterazioni

Nell'esempio seguente utilizziamo il metodo filter(). Qui puoi vedere che il codice è ottimizzato e molto conciso.

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

Produzione:

 Dell Laptop 

Esempio di flusso Java: metodo reduce() nella raccolta

Questo metodo prende una sequenza di elementi di input e li combina in un unico risultato riepilogativo mediante operazioni ripetute. Ad esempio, trovare la somma di numeri o accumulare elementi in un elenco.

Nell'esempio seguente, utilizziamo il metodo reduce(), che viene utilizzato per sommare tutti i prezzi dei prodotti.

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

Produzione:

 201000.0 201000.0 

Esempio di flusso Java: somma utilizzando i metodi di raccolta

Possiamo anche utilizzare i collezionisti per calcolare la somma di valori numerici. Nell'esempio seguente, stiamo utilizzando la classe Collectors e i suoi metodi specificati per calcolare la somma di tutti i prezzi dei prodotti.

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

Produzione:

 201000.0 

Esempio di flusso Java: trovare il prezzo massimo e minimo del prodotto

L'esempio seguente trova il prezzo minimo e massimo del prodotto utilizzando il flusso. Fornisce un modo conveniente per trovare valori senza utilizzare l'approccio imperativo.

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

Produzione:

 90000.0 25000.0 

Esempio di flusso Java: metodo count() nella raccolta

 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 ti consente di raccogliere i risultati in varie forme. Puoi ottenere i risultati come set, elenco o mappa ed eseguire manipolazioni sugli elementi.


Esempio di flusso Java: converti elenco in set

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

Produzione:

 [25000.0, 28000.0] 

Esempio di flusso Java: converti l'elenco in una mappa

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

Produzione:

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

Riferimento al metodo nel flusso

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

Produzione:

 [90000.0]