Tutorial Java 8 Stream Kanthi Conto Code

Ing postingan blog iki, kita bakal ngrembug fitur Java 8 Streams lan menehi conto conto kode sing beda.

Java Streams nggawa program fungsional menyang java lan didhukung wiwit ing jawa 8 dadi yen sampeyan duwe versi jawa lawas, mula sampeyan kudu nganyari menyang java 8 kanggo nggunakake Java Streams.



Napa Nggunakake stream Java?

Sawetara kaluwihan stream:


  • Aliran bakal ndadekake sampeyan dadi programmer java sing luwih efisien (sampeyan bakal bisa ndeleng manawa sawetara garis kode sampeyan bisa entuk akeh nggunakake stream).
  • Dheweke nggunakake ekspresi lambda sing abot yaiku fungsi sing bisa digunakake.
  • ParallelStreams nggawe operasi multi-Utas kanggo data gedhe kanthi gampang.


Aliran Pipa

Ing kasus paling umum, pipa lepen kalebu a

  • sumber (ing endi data sampeyan metu)
  • ngiring dening nul utawa luwih operasi penengah
  • lan siji operasi terminal

Aliran Java - Filter, Peta, Kurangi


Sumber kasebut bakal ngalir stream elemen.



Aliran elemen kasebut bisa disaring, diurutake, utawa bisa dipetakan utawa macem-macem seri operasi liyane sing ditrapake kanggo saben elemen.

Ing pungkasan, bisa diklumpukake utawa dikurangi utawa sawetara operasi terminal liyane nanging mung siji operasi terminal sing ditindakake.

Sumber Aliran

Sumber stream bisa asale saka koleksi, dhaptar, set, susunan int, kangen, dobel, senar lsp.


Operasi Aliran

Operasi stream ana ing antarane utawa ing terminal:

  • Operasi penengah kayata filter, peta, utawa sortir ngasilake stream supaya bisa nggawe macem-macem operasi menengah.
  • Operasi terminal nampa stream lan bisa ngasilake batal utawa bisa ngasilake asil non stream kayata nyuda, f.eks. nyuda item menyang dhaptar.

Operasi Menengah

  • Operasi nol utawa luwih penengah diidini.
  • Urusan prentah; kanggo dhata gedhe: saring dhisik banjur diurutake utawa peta.
  • Kanggo susunan data sing gedhe banget, ParallelStream ngaktifake macem-macem utas.

Sawetara operasi penengah kalebu:

  • anyMatch ()
  • beda ()
  • saringan ()
  • findFirst ()
  • flatmap ()
  • peta ()
  • nglumpati ()
  • diurutake ()

Operasi Terminal

Mung diijini operasi terminal.

  • kanggoEach ngetrapake fungsi sing padha kanggo saben elemen kayata nyithak saben elemen.
  • nglumpukake nyimpen kabeh elemen menyang koleksi utawa dhaptar utawa susunan.
  • kabeh opsi liyane nyuda stream menyang elemen ringkesan siji.

Sawetara conto nyuda fungsi yaiku:


  • ngetung ()
  • max ()
  • min ()
  • nyuda ()


Tuladha Kode Aliran Java

Saiki ayo ndeleng konsep ing ndhuwur ing conto kode.

Stream Integer

Contone pisanan mung stream wilangan bulat. Kita bakal nggawe stream wilangan bulat nggunakake IntStream fungsi kelas lan jangkoan sing menehi macem-macem bilangan bulat.

Sing forEach yaiku operasi terminal kita. Kanggo saben item, kita mung bakal nyithak.

import java.io.IOException; import java.util.stream.IntStream; public class JavaStreams {
public static void main(String[] args) throws IOException {
IntStream

.range(1, 10)

.forEach(System.out::print);
System.out.println();
} }

Output:


123456789

Stream Integer nganggo Skip

Tuladha nomer loro nggunakake stream ongko ongko nanging kita nambahake skip() ing kene, dadi ing kasus iki, kita bakal ngilangi 5 elemen pertama stream kita.

Iki mung bakal nyithak elemen 6 nganti 9. Kita uga nggunakake ekspresi lambda sing gampang kanggo nyithak item kasebut

import java.io.IOException; import java.util.stream.IntStream; public class JavaStreams {
public static void main(String[] args) throws IOException {
IntStream

.range(1, 10)

.skip(5)

.forEach(x -> System.out.println(x));
System.out.println();
} }

Output:

6 7 8 9

Integer Stream karo Jumlah

Contone kaping telu, maneh nganggo IntStream nanging kanggo nggawe aliran obyek, kita sijine ing njero a println() pratelan minangka paramèter kanggo garis cetak.


Sing bakal dicithak mung jumlah saka kisaran 1 nganti 5 kanthi tembung liyane, 1 2 3 & 4 mung bakal nyithak jumlah kasebut:

import java.io.IOException; import java.util.stream.IntStream; public class JavaStreams {
public static void main(String[] args) throws IOException {
System.out.println(
IntStream

.range(1, 5)

.sum());
System.out.println();
} }

Output:

10

Stream.of

Tuladha sabanjure nggunakake Stream.of fungsi, sing pancen gampang banget amarga sampeyan bisa streaming wilangan bulat, angka titik ngambang utawa senar utawa uga obyek.

Ing conto iki, kita mung bakal nindakake urutan abjad sing lurus banjur bakal nemokake item pisanan nggunakake findFirst() fungsi Banjur, kita mung nyithak item pisanan ing dhaptar.

import java.io.IOException; import java.util.stream.Stream; public class JavaStreams {
public static void main(String[] args) throws IOException {
Stream.of('Ava', 'Aneri', 'Alberto')

.sorted()

.findFirst()

.ifPresent(System.out::println);
} }

Output

Alberto

Stream saka Array, sort, filter lan print

Ing conto sabanjure, kita bakal stream saka larik. Banjur kita bakal ngurutake, nyaring banjur nyithak.

Ing kene, kita bakal nyaring item mung sing diwiwiti karo s.

Kita nggunakake ekspresi lambda sing ana X sing saben jeneng banjur mriksa sing diwiwiti nganggo huruf s lan bakal ngliwati sing.

Banjur kita bakal ngurutake lan banjur kanggo saben item sing liwat, kita bakal nyithak.

import java.io.IOException; import java.util.Arrays; public class JavaStreams {
public static void main(String[] args) throws IOException {
String[] names = {'Al', 'Ankit', 'Kushal', 'Brent', 'Sarika', 'amanda', 'Hans', 'Shivika', 'Sarah'};
Arrays.stream(names)


.filter(x -> x.startsWith('S'))


.sorted()


.forEach(System.out::println);
} }

Output:

Sarah Sarika Shivika

Rata-rata Array Integer

Saiki ayo goleki kepiye cara bisa njupuk rata-rata kotak saka susunan int.

Ing kene, kita nggunakake Arrays.stream() fungsi kanggo stream ongko wilangan banjur bakal nggunakake map() kanggo peta saben item saben bilangan bulat menyang kothak.

import java.util.Arrays; public class JavaStreams {
public static void main(String[] args) {
Arrays.stream(new int[] {2, 4, 6, 8, 10})


.map(x -> x * x)


.average()


.ifPresent(System.out::println);
} }

Output:

44.0

Elinga yen dicithak kaping pindho tinimbang bilangan bulat.

Stream saka Dhaptar, saringan lan cetak

Ing conto iki, kita bakal stream saka dhaptar, nyaring barang kasebut banjur dicithak.

Elinga yen ing map() fungsi, kita bakal ngowahi kabeh jeneng dadi huruf cilik.

import java.util.Arrays; import java.util.List; public class JavaStreams {
public static void main(String[] args) {
List people = Arrays.asList('Al', 'Ankit', 'Brent', 'Sarika', 'amanda', 'Hans', 'Shivika', 'Sarah');
people


.stream()


.map(String::toLowerCase)


.filter(x -> x.startsWith('a'))


.forEach(System.out::println);
} }

Output:

al ankit amanda

Kita bisa ndeleng duwe telung jeneng sing diwiwiti karo a lan dheweke kabeh ana ing huruf cilik.

Baris stream saka file teks, sort, filter, lan print

Ing conto sabanjure, kita bakal stream baris saka file teks. Kita bakal ngurutake, nyaring lan nyithak.

Ayo dadi nganggep duwe file sing diarani bands.txt kanthi isi sing kapacak ing ngisor iki:

Rolling Stones Lady Gaga Jackson Browne Maroon 5 Arijit Singh Elton John John Mayer CCR Eagles Pink Aerosmith Adele Taylor Swift

Kita bakal nggunakake Files.lines() kanggo nggawe stream sing bakal menehi stream kanggo saben baris file.

Sawise duwe aliran, kita bakal ngurutake lan bakal nyaring item sing luwih saka 13 karakter banjur nyithak item sing isih ana.

Pungkasan, kita kudu nutup file supaya bisa nindakake bands.close.

import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.stream.Stream; public class JavaStreams {
public static void main(String[] args) throws IOException {
Stream bands = Files.lines(Paths.get('bands.txt'));
bands


.sorted()


.filter(x -> x.length() > 13)


.forEach(System.out::println);
bands.close();
} }

Output:

Jackson Browne Rolling Stones

Kita entuk rong band sing duwe luwih saka 13 karakter.

Streaming baris saka file teks lan simpen menyang Dhaptar

Contone iki, kita bakal nggunakake file teks kaya ing ndhuwur.

Kita pengin nyaring barang sing isine huruf jit, nggunakake x.contains() sing mung fungsi senar.

Nggunakake .collect() kita nambahake kabeh nganggo aksara jit menyang dhaptar.

Yen wis ora ana dhaptar, mula banjur bisa nggunakake forEach operator kanggo nyithak item kasebut.

import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; import java.util.stream.Collectors; public class JavaStreams {
public static void main(String[] args) throws IOException {
List bands2 = Files.lines(Paths.get('bands.txt'))


.filter(x -> x.contains('jit'))


.collect(Collectors.toList());
bands2.forEach(x -> System.out.println(x));
} }

Output:

Arijit Singh

Baris stream saka file CSV lan dietung

Ing conto iki, kita stream baris saka file CSV lan bakal ngetung larik sing apik.

Upamane kita duwe file sing diarani data.txt kanthi isine kaya ing ngisor iki:

A,12,3.7 B,17,2.8 C,14,1.9 D,23,2.7 E F,18,3.4

Ing kene, baris E ora duwe data, mula kita pengin ngilangi sing siji saka stream kita.

Ing kode ing ngisor iki, kita bakal maca ing saben baris banjur kudu pamisah koma dadi larik supaya saben baris bakal dadi macem-macem barang.

Banjur aplikasi filter kanggo nyaring larik sing ora ana telung item.

import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.stream.Stream; public class JavaStreams {
public static void main(String[] args) throws IOException {
Stream rows1 = Files.lines(Paths.get('data.txt'));
int rowCount = (int)rows1


.map(x -> x.split(','))


.filter(x -> x.length == 3)


.count();
System.out.println(rowCount + ' rows.');
rows1.close();
} }

Output:

5 rows

Pengirangan - jumlah

Contone iki nuduhake sampeyan cara nggunakake pangurangan. Kita bakal nyuda dadi jumlah. Ing kene, kita duwe stream dobel nggunakake Stream.of() fungsi Kita wis nemtokake telung dobel ing telung bantahan sing beda lan kita bakal nggunakake fungsi nyuda.

import java.util.stream.Stream; public class JavaStreams {
public static void main(String[] args) {
double total = Stream.of(7.3, 1.5, 4.8)


.reduce(0.0, (Double a, Double b) -> a + b);
System.out.println('Total = ' + total);
} }

Output:

13.600000000000001