Java nudi novi dodatni paket u Javi 8 pod nazivom java.util.stream. Ovaj paket se sastoji od klasa, sučelja i enuma koji omogućuju operacije u funkcionalnom stilu na elementima. Možete koristiti stream uvozom paketa java.util.stream.
Stream pruža sljedeće značajke:
- Stream ne pohranjuje elemente. Jednostavno prenosi elemente iz izvora kao što je struktura podataka, polje ili I/O kanal, kroz cjevovod računalnih operacija.
- Struja je funkcionalne prirode. Operacije koje se izvode na streamu ne mijenjaju njegov izvor. Na primjer, filtriranje streama dobivenog iz zbirke proizvodi novi stream bez filtriranih elemenata, umjesto uklanjanja elemenata iz izvorne zbirke.
- Stream je lijen i procjenjuje kod samo kada je to potrebno.
- Elementi streama posjećuju se samo jednom tijekom života streama. Poput iteratora, mora se generirati novi tok da bi se ponovno posjetili isti elementi izvora.
Možete koristiti stream za filtriranje, prikupljanje, ispis i pretvaranje iz jedne podatkovne strukture u drugu itd. U sljedećim primjerima primijenili smo različite operacije uz pomoć streama.
Metode Java Stream sučelja
Metode | Opis |
---|---|
boolean allMatch(predikat predikat) | Vraća sve elemente ovog toka koji odgovaraju navedenom predikatu. Ako je tok prazan, vraća se true i predikat se ne procjenjuje. |
boolean anyMatch(predikat predikat) | Vraća svaki element ovog toka koji odgovara navedenom predikatu. Ako je tok prazan, tada se vraća false i predikat se ne procjenjuje. |
statički Stream.Builder builder() | Vraća builder za Stream. |
R collect(Kolekcionar kolektor) | Izvodi promjenjivu operaciju redukcije na elementima ovog toka pomoću kolektora. Skupljač sažima funkcije koje se koriste kao argumenti za prikupljanje (Dobavljač, BiPotrošač, BiPotrošač), dopuštajući ponovnu upotrebu strategija prikupljanja i sastav operacija prikupljanja kao što je grupiranje ili particioniranje na više razina. |
R prikupljanje (dobavljač dobavljač, BiConsumer akumulator, BiConsumer combiner) | Izvodi promjenjivu operaciju redukcije na elementima ovog toka. Promjenjiva redukcija je ona u kojoj je smanjena vrijednost promjenjivi spremnik rezultata, kao što je ArrayList, a elementi su ugrađeni ažuriranjem stanja rezultata, a ne zamjenom rezultata. |
statički Stream concat(Stream a, Stream b) | Stvara lijeno spojeni tok čiji su elementi svi elementi prvog toka praćeni svim elementima drugog toka. Rezultirajući tok je uređen ako su oba ulazna toka poredana, a paralelan ako je bilo koji od ulaznih tokova paralelan. Kada se rezultirajući tok zatvori, pozivaju se rukovatelji zatvaranja za oba ulazna toka. |
dugo brojanje() | Vraća broj elemenata u ovom toku. Ovo je poseban slučaj redukcije. |
Stream distinct() | Vraća tok koji se sastoji od različitih elemenata (prema Object.equals(Object)) ovog toka. |
statički tok prazan() | Vraća prazan sekvencijalni tok. |
Filtar toka (predikat predikat) | Vraća tok koji se sastoji od elemenata ovog toka koji odgovaraju zadanom predikatu. |
Neobavezno findAny() | Vraća Optional koji opisuje neki element toka ili prazan Optional ako je tok prazan. |
Neobavezno findFirst() | Vraća Optional koji opisuje prvi element ovog toka ili prazan Optional ako je tok prazan. Ako tok nema redoslijed susreta, tada se može vratiti bilo koji element. |
Stream flatMap(funkcija super T,? extends Stream>maper) | Vraća tok koji se sastoji od rezultata zamjene svakog elementa ovog toka sa sadržajem mapiranog toka proizvedenog primjenom dane funkcije preslikavanja na svaki element. Svaki mapirani tok se zatvara nakon što se njegov sadržaj smjesti u ovaj tok. (Ako je mapirani tok null, umjesto njega se koristi prazan tok.) |
DoubleStream flatMapToDouble(Maper funkcije) | Vraća DoubleStream koji se sastoji od rezultata zamjene svakog elementa ovog toka sa sadržajem mapiranog toka proizvedenog primjenom dane funkcije mapiranja na svaki element. Svaki mapirani tok se zatvara nakon što se njegov sadržaj smjesti u ovaj tok. (Ako je mapirani tok null, umjesto njega se koristi prazan tok.) |
IntStream flatMapToInt(Maper funkcije) | Vraća IntStream koji se sastoji od rezultata zamjene svakog elementa ovog toka sa sadržajem mapiranog toka proizvedenog primjenom dane funkcije mapiranja na svaki element. Svaki mapirani tok se zatvara nakon što se njegov sadržaj smjesti u ovaj tok. (Ako je mapirani tok null, umjesto njega se koristi prazan tok.) |
LongStream flatMapToLong(Maper funkcije) | Vraća LongStream koji se sastoji od rezultata zamjene svakog elementa ovog toka sa sadržajem mapiranog toka proizvedenog primjenom dane funkcije mapiranja na svaki element. Svaki mapirani tok se zatvara nakon što se njegov sadržaj smjesti u ovaj tok. (Ako je mapirani tok null, umjesto njega se koristi prazan tok.) |
void forEach(radnja potrošača) | Izvodi radnju za svaki element ovog toka. |
void forEachOrdered(radnja potrošača) | Izvodi radnju za svaki element ovog toka, u redoslijedu susreta toka ako tok ima definiran redoslijed susreta. |
generiranje statičkog toka (dobavljači) | Vraća beskonačni sekvencijalni neuređeni tok gdje svaki element generira navedeni Dobavljač. Ovo je prikladno za generiranje konstantnih tokova, tokova slučajnih elemenata itd. |
static Stream iterate(T seed,UnaryOperator f) | Vraća beskonačni sekvencijalni uređeni tok proizveden iterativnom primjenom funkcije f na početno sjeme elementa, proizvodeći tok koji se sastoji od sjemena, f(seed), f(f(seed)), itd. |
Ograničenje streama (duga maks. veličina) | Vraća tok koji se sastoji od elemenata ovog toka, skraćenih da ne budu dulji od maxSize. |
Mapa toka (Maper funkcije) | Vraća tok koji se sastoji od rezultata primjene zadane funkcije na elemente ovog toka. |
DoubleStream mapToDouble(ToDoubleFunction maper) | Vraća DoubleStream koji se sastoji od rezultata primjene zadane funkcije na elemente ovog toka. |
IntStream mapToInt(ToIntFunction maper) | Vraća IntStream koji se sastoji od rezultata primjene zadane funkcije na elemente ovog toka. | LongStream mapToLong(ToLongFunction maper) | Vraća LongStream koji se sastoji od rezultata primjene zadane funkcije na elemente ovog toka. |
Dodatni max (komparator komparator) | Vraća maksimalni element ovog toka prema dostavljenom usporedniku. Ovo je poseban slučaj redukcije. |
Izborni min (komparator komparator) | Vraća minimalni element ovog toka prema dostavljenom Comparatoru. Ovo je poseban slučaj redukcije. |
boolean noneMatch(predikat predikat) | Vraća elemente ovog toka koji odgovaraju navedenom predikatu. Ako je tok prazan, vraća se true i predikat se ne procjenjuje. |
@SafeVarargs statički tok (T... vrijednosti) | Vraća sekvencijalni poredani tok čiji su elementi navedene vrijednosti. |
statički tok (T t) | Vraća sekvencijalni tok koji sadrži jedan element. |
Stream peek (radnja potrošača) | Vraća tok koji se sastoji od elemenata ovog toka, dodatno izvodeći predviđenu radnju na svakom elementu kako se elementi troše iz rezultirajućeg toka. |
Izborno smanjenje (BinaryOperator akumulator) | Izvodi redukciju na elementima ovog toka, koristeći funkciju asocijativne akumulacije, i vraća opciju koja opisuje smanjenu vrijednost, ako postoji. |
T reducirati (T identitet, akumulator binarnog operatora) | Izvodi redukciju na elementima ovog toka, koristeći osiguranu vrijednost identiteta i funkciju asocijativne akumulacije, i vraća smanjenu vrijednost. |
U reducirati (U identitet, BiFunction akumulator, BinaryOperator combiner) | Izvodi redukciju elemenata ovog toka, koristeći dane funkcije identiteta, akumulacije i kombiniranja. |
Preskakanje streama (dugo n) | Vraća tok koji se sastoji od preostalih elemenata ovog toka nakon odbacivanja prvih n elemenata toka. Ako ovaj tok sadrži manje od n elemenata, tada će se vratiti prazan tok. |
Stream sortiran() | Vraća tok koji se sastoji od elemenata ovog toka, sortiranih prema prirodnom redoslijedu. Ako elementi ovog toka nisu usporedivi, java.lang.ClassCastException može biti izbačen kada se operacija terminala izvrši. |
Tok sortiran (komparator komparator) | Vraća tok koji se sastoji od elemenata ovog toka, sortiranih prema dostavljenom usporedniku. |
Object[] toArray() | Vraća niz koji sadrži elemente ovog toka. |
A[] toArray(IntFunction generator) | Vraća niz koji sadrži elemente ovog toka, koristeći osiguranu funkciju generatora za dodjelu vraćenog niza, kao i sve dodatne nizove koji bi mogli biti potrebni za particionirano izvođenje ili za promjenu veličine. |
Java primjer: Filtriranje zbirke bez korištenja Streama
U sljedećem primjeru filtriramo podatke bez korištenja toka. Ovaj pristup smo koristili prije izdavanja paketa streama.
web stranica poput coomeeta
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,'HP Laptop',25000f)); productsList.add(new Product(2,'Dell Laptop',30000f)); productsList.add(new Product(3,'Lenevo Laptop',28000f)); productsList.add(new Product(4,'Sony Laptop',28000f)); productsList.add(new Product(5,'Apple Laptop',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,'HP Laptop',25000f)); productsList.add(new Product(2,'Dell Laptop',30000f)); productsList.add(new Product(3,'Lenevo Laptop',28000f)); productsList.add(new Product(4,'Sony Laptop',28000f)); productsList.add(new Product(5,'Apple Laptop',90000f)); List productPriceList2 =productsList.stream() .filter(p -> p.price > 30000)// filtering data .map(p->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->element+1) .filter(element->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,'HP Laptop',25000f)); productsList.add(new Product(2,'Dell Laptop',30000f)); productsList.add(new Product(3,'Lenevo Laptop',28000f)); productsList.add(new Product(4,'Sony Laptop',28000f)); productsList.add(new Product(5,'Apple Laptop',90000f)); // This is more compact approach for filtering data productsList.stream() .filter(product -> product.price == 30000) .forEach(product -> 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,'HP Laptop',25000f)); productsList.add(new Product(2,'Dell Laptop',30000f)); productsList.add(new Product(3,'Lenevo Laptop',28000f)); productsList.add(new Product(4,'Sony Laptop',28000f)); productsList.add(new Product(5,'Apple Laptop',90000f)); // This is more compact approach for filtering data Float totalPrice = productsList.stream() .map(product->product.price) .reduce(0.0f,(sum, price)->sum+price); // accumulating price System.out.println(totalPrice); // More precise code float totalPrice2 = productsList.stream() .map(product->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,'HP Laptop',25000f)); productsList.add(new Product(2,'Dell Laptop',30000f)); productsList.add(new Product(3,'Lenevo Laptop',28000f)); productsList.add(new Product(4,'Sony Laptop',28000f)); productsList.add(new Product(5,'Apple Laptop',90000f)); // Using Collectors's method to sum the prices. double totalPrice3 = productsList.stream() .collect(Collectors.summingDouble(product->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,'HP Laptop',25000f)); productsList.add(new Product(2,'Dell Laptop',30000f)); productsList.add(new Product(3,'Lenevo Laptop',28000f)); productsList.add(new Product(4,'Sony Laptop',28000f)); productsList.add(new Product(5,'Apple Laptop',90000f)); // max() method to get max Product price Product productA = productsList.stream().max((product1, product2)->product1.price > product2.price ? 1: -1).get(); System.out.println(productA.price); // min() method to get min Product price Product productB = productsList.stream().min((product1, product2)->product1.price > 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,'HP Laptop',25000f)); productsList.add(new Product(2,'Dell Laptop',30000f)); productsList.add(new Product(3,'Lenevo Laptop',28000f)); productsList.add(new Product(4,'Sony Laptop',28000f)); productsList.add(new Product(5,'Apple Laptop',90000f)); // count number of products based on the filter long count = productsList.stream() .filter(product->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,'HP Laptop',25000f)); productsList.add(new Product(2,'Dell Laptop',30000f)); productsList.add(new Product(3,'Lenevo Laptop',28000f)); productsList.add(new Product(4,'Sony Laptop',28000f)); productsList.add(new Product(5,'Apple Laptop',90000f)); // Converting product List into Set Set productPriceList = productsList.stream() .filter(product->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,'HP Laptop',25000f)); productsList.add(new Product(2,'Dell Laptop',30000f)); productsList.add(new Product(3,'Lenevo Laptop',28000f)); productsList.add(new Product(4,'Sony Laptop',28000f)); productsList.add(new Product(5,'Apple Laptop',90000f)); // Converting Product List into a Map Map productPriceMap = productsList.stream() .collect(Collectors.toMap(p->p.id, p->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,'HP Laptop',25000f)); productsList.add(new Product(2,'Dell Laptop',30000f)); productsList.add(new Product(3,'Lenevo Laptop',28000f)); productsList.add(new Product(4,'Sony Laptop',28000f)); productsList.add(new Product(5,'Apple Laptop',90000f)); List productPriceList = productsList.stream() .filter(p -> p.price > 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){>
Primjer Java Stream-a: Filtriranje zbirke korištenjem Stream-a
Ovdje filtriramo podatke pomoću streama. Možete vidjeti da je kod optimiziran i održavan. Stream omogućuje brzo izvršenje.
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,'HP Laptop',25000f)); productsList.add(new Product(2,'Dell Laptop',30000f)); productsList.add(new Product(3,'Lenevo Laptop',28000f)); productsList.add(new Product(4,'Sony Laptop',28000f)); productsList.add(new Product(5,'Apple Laptop',90000f)); List productPriceList2 =productsList.stream() .filter(p -> p.price > 30000)// filtering data .map(p->p.price) // fetching price .collect(Collectors.toList()); // collecting as list System.out.println(productPriceList2); } }
Izlaz:
[90000.0]
Primjer ponavljanja Java toka
Možete koristiti stream za ponavljanje neograničeni broj puta. Stream nudi unaprijed definirane metode za rješavanje logike koju implementirate. U sljedećem primjeru ponavljamo, filtriramo i proslijedili smo ograničenje kako bismo popravili ponavljanje.
import java.util.stream.*; public class JavaStreamExample { public static void main(String[] args){ Stream.iterate(1, element->element+1) .filter(element->element%5==0) .limit(5) .forEach(System.out::println); } }
Izlaz:
5 10 15 20 25
Primjer Java toka: Filtriranje i ponavljanje zbirke
U sljedećem primjeru koristimo metodu filter(). Ovdje možete vidjeti da je kod optimiziran i vrlo koncizan.
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,'HP Laptop',25000f)); productsList.add(new Product(2,'Dell Laptop',30000f)); productsList.add(new Product(3,'Lenevo Laptop',28000f)); productsList.add(new Product(4,'Sony Laptop',28000f)); productsList.add(new Product(5,'Apple Laptop',90000f)); // This is more compact approach for filtering data productsList.stream() .filter(product -> product.price == 30000) .forEach(product -> System.out.println(product.name)); } }
Izlaz:
Dell Laptop
Primjer Java toka: metoda reduce() u kolekciji
Ova metoda uzima niz ulaznih elemenata i kombinira ih u jedan sažeti rezultat ponovljenom operacijom. Na primjer, pronalaženje zbroja brojeva ili gomilanje elemenata u popis.
U sljedećem primjeru koristimo metodu reduce(), koja se koristi za zbrajanje svih cijena proizvoda.
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,'HP Laptop',25000f)); productsList.add(new Product(2,'Dell Laptop',30000f)); productsList.add(new Product(3,'Lenevo Laptop',28000f)); productsList.add(new Product(4,'Sony Laptop',28000f)); productsList.add(new Product(5,'Apple Laptop',90000f)); // This is more compact approach for filtering data Float totalPrice = productsList.stream() .map(product->product.price) .reduce(0.0f,(sum, price)->sum+price); // accumulating price System.out.println(totalPrice); // More precise code float totalPrice2 = productsList.stream() .map(product->product.price) .reduce(0.0f,Float::sum); // accumulating price, by referring method of Float class System.out.println(totalPrice2); } }
Izlaz:
201000.0 201000.0
Primjer Java Stream-a: zbrajanje korištenjem metoda sakupljača
Također možemo koristiti kolektore za izračunavanje zbroja numeričkih vrijednosti. U sljedećem primjeru koristimo klasu Collectors i njene specificirane metode za izračunavanje zbroja svih cijena proizvoda.
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,'HP Laptop',25000f)); productsList.add(new Product(2,'Dell Laptop',30000f)); productsList.add(new Product(3,'Lenevo Laptop',28000f)); productsList.add(new Product(4,'Sony Laptop',28000f)); productsList.add(new Product(5,'Apple Laptop',90000f)); // Using Collectors's method to sum the prices. double totalPrice3 = productsList.stream() .collect(Collectors.summingDouble(product->product.price)); System.out.println(totalPrice3); } }
Izlaz:
201000.0
Primjer Java streama: Pronađite maksimalnu i minimalnu cijenu proizvoda
Sljedeći primjer pronalazi minimalnu i maksimalnu cijenu proizvoda pomoću toka. Omogućuje prikladan način za pronalaženje vrijednosti bez korištenja imperativnog pristupa.
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,'HP Laptop',25000f)); productsList.add(new Product(2,'Dell Laptop',30000f)); productsList.add(new Product(3,'Lenevo Laptop',28000f)); productsList.add(new Product(4,'Sony Laptop',28000f)); productsList.add(new Product(5,'Apple Laptop',90000f)); // max() method to get max Product price Product productA = productsList.stream().max((product1, product2)->product1.price > product2.price ? 1: -1).get(); System.out.println(productA.price); // min() method to get min Product price Product productB = productsList.stream().min((product1, product2)->product1.price > product2.price ? 1: -1).get(); System.out.println(productB.price); } }
Izlaz:
90000.0 25000.0
Primjer Java toka: metoda count() u kolekciji
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,'HP Laptop',25000f)); productsList.add(new Product(2,'Dell Laptop',30000f)); productsList.add(new Product(3,'Lenevo Laptop',28000f)); productsList.add(new Product(4,'Sony Laptop',28000f)); productsList.add(new Product(5,'Apple Laptop',90000f)); // count number of products based on the filter long count = productsList.stream() .filter(product->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,'HP Laptop',25000f)); productsList.add(new Product(2,'Dell Laptop',30000f)); productsList.add(new Product(3,'Lenevo Laptop',28000f)); productsList.add(new Product(4,'Sony Laptop',28000f)); productsList.add(new Product(5,'Apple Laptop',90000f)); // Converting product List into Set Set productPriceList = productsList.stream() .filter(product->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,'HP Laptop',25000f)); productsList.add(new Product(2,'Dell Laptop',30000f)); productsList.add(new Product(3,'Lenevo Laptop',28000f)); productsList.add(new Product(4,'Sony Laptop',28000f)); productsList.add(new Product(5,'Apple Laptop',90000f)); // Converting Product List into a Map Map productPriceMap = productsList.stream() .collect(Collectors.toMap(p->p.id, p->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,'HP Laptop',25000f)); productsList.add(new Product(2,'Dell Laptop',30000f)); productsList.add(new Product(3,'Lenevo Laptop',28000f)); productsList.add(new Product(4,'Sony Laptop',28000f)); productsList.add(new Product(5,'Apple Laptop',90000f)); List productPriceList = productsList.stream() .filter(p -> p.price > 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 vam omogućuje prikupljanje rezultata u različitim oblicima. Rezultat možete dobiti kao skup, popis ili kartu i možete manipulirati elementima.
Primjer Java toka: Pretvori popis u skup
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,'HP Laptop',25000f)); productsList.add(new Product(2,'Dell Laptop',30000f)); productsList.add(new Product(3,'Lenevo Laptop',28000f)); productsList.add(new Product(4,'Sony Laptop',28000f)); productsList.add(new Product(5,'Apple Laptop',90000f)); // Converting product List into Set Set productPriceList = productsList.stream() .filter(product->product.price product.price) .collect(Collectors.toSet()); // collect it as Set(remove duplicate elements) System.out.println(productPriceList); } }
Izlaz:
[25000.0, 28000.0]
Primjer Java toka: Pretvorite popis u kartu
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,'HP Laptop',25000f)); productsList.add(new Product(2,'Dell Laptop',30000f)); productsList.add(new Product(3,'Lenevo Laptop',28000f)); productsList.add(new Product(4,'Sony Laptop',28000f)); productsList.add(new Product(5,'Apple Laptop',90000f)); // Converting Product List into a Map Map productPriceMap = productsList.stream() .collect(Collectors.toMap(p->p.id, p->p.name)); System.out.println(productPriceMap); } }
Izlaz:
{1=HP Laptop, 2=Dell Laptop, 3=Lenevo Laptop, 4=Sony Laptop, 5=Apple Laptop}
Referenca metode u toku
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,'HP Laptop',25000f)); productsList.add(new Product(2,'Dell Laptop',30000f)); productsList.add(new Product(3,'Lenevo Laptop',28000f)); productsList.add(new Product(4,'Sony Laptop',28000f)); productsList.add(new Product(5,'Apple Laptop',90000f)); List productPriceList = productsList.stream() .filter(p -> p.price > 30000) // filtering data .map(Product::getPrice) // fetching price by referring getPrice method .collect(Collectors.toList()); // collecting as list System.out.println(productPriceList); } }
Izlaz:
[90000.0]
30000)>30000){>