Quantcast
Channel: Appu The Engineer
Viewing all articles
Browse latest Browse all 6

Stream in Java

$
0
0

Interoduction

Streams bring functional programming to java and are supported starting in java 8

Advantages of streams

  • Make heavy use of lambda expression
  • Parallel streams make it very easy to multi-thread operations
  • Will make you a more efficient java programmer

A stream pipeline consists of a source, followed by zero or more intermediate operations and a terminal operation.

Untitled Diagram

Stream Source

  • Streams can be created from Collection, Lists, Sets, ints, longs, doubles, arrays, lines of a file

Stream operations are either intermediate or terminal.

  • Intermediate operations such as filter, map or sort return a stream so we can chain multiple intermediate operations.
  • Terminal operations such as forEach, collect or reduce are either void or return a non-stream result.

Intermediate Operations

Zero or more intermediate operations are allowed.

Order matters for large datasets: filter first, then sort or map.

For very large datasets use ParallelStream to enable multiple threads.

Intermediate operations include :

anyMatch()

flatmap()

distinct()

map()

filter()

skip()

findFirst()

sorted()

Terminal Operations

One terminal operation is allowed.

forEach applies the same function to each element.

collect saves the elements into a collection.

Other options reduce the stream to a single summary element.

count() min()
max() reduce()
summaryStatics()

Getting bored ? don’t worry lets try to understand by practical examples :

public class JavaStreams {
    public static void main(String[] args) throws IOException {

        // 1. Integer Stream
        IntStream
                .range(1,10)
                .forEach(System.out::print);
        System.out.println();
    }
}
Output : 123456789

IntStream is one of the stream defined in java.util.stream it will provide all integer in stream.

range(1,10) –  It is intermediate operation which will provide integers  1,2,3,4,5,6,7,8,9

forEach() – Terminal operation which will iterate all integers and system.out::println will print each integer iterated by forEach()

Stream allow use to perform n number of intermediate operations. Lets see the example:

public class JavaStreams {
    public static void main(String[] args) throws IOException {

        // 2. Integer Stream with skip
        IntStream
                .range(1,10)
                .skip(5)
                .forEach(x -> System.out.println(x));
        System.out.println();
    }
}
Output
6
7
8
9

skip(5) will skip first 5 integers which are 1,2,3,4,5

Lets perform addition in the stream

public class JavaStreams {
    public static void main(String[] args) throws IOException {

       // 3. Integer Stream with sum
        System.out.println(
                IntStream
                        .range(1,5)
                        .sum());
        System.out.println();
    }
}
Output : 10

sum() will add all integers before 5 and starting from 1.

We can sort items very quickly in stream

public class JavaStreams {
    public static void main(String[] args) throws IOException {

       // 4. Stream.of, sorted and findFirst
        Stream.of("Appu","Aneri","Alberto")
                .sorted()
                .findFirst()
                .ifPresent(System.out::println);
        System.out.println();
    }
}
Output : Alberto

Stream.of() – will convert elements in stream.

sorted() – will sort all elements.

firstFirst() – will find first element of the sorted stream

ifPresent() –  will check if there is any element available in the stream

We can convert array of any elements into stream by Arrays.stream()

public class JavaStreams {
    public static void main(String[] args) throws IOException {

       // 5. Stream from Array, sort, filter and print
        String[] names = {"Al","Ankit","Kushal","Brent","Sarika","amanda","Hans","Shivika"};
        Arrays.stream(names)
                .filter(x->x.startsWith("S"))
                .sorted()
                .forEach(System.out::println);
        System.out.println();
    }
}
Output : 
Sarika
Shivika

filter() – will only allow names which starts with ‘S’ character.

Lets stream array of integers and perform average of squares :

public class JavaStreams {
    public static void main(String[] args) throws IOException {

       // 6. average of squares of an int array
        Arrays.stream(new int[] {2,4,6,8,10})
                .map(x->x*x)
                .average()
                .ifPresent(System.out::println);
        System.out.println();
    }
}
Output : 44

map(x-> x*x) – will iterate each element and square the value.

average() – calculate average of all elements

We can also get stream from list :

public class JavaStreams {
    public static void main(String[] args) throws IOException {

       // 7. Stream from List, filter and print
        List people = Arrays.asList("Al","Appu","Brent","Sarika","amanda","Hans");
        people
            .stream()
            .map(String::toLowerCase)
            .filter(x -> x.startsWith("a"))
            .forEach(System.out::println);
        System.out.println();
   }
}
Output : 
al
appu
amanda

String::toLowerCase will change case of each element to lowerCase.

We can stream rows from text file and perform needed actions.

Lets create a file name bands.txt and put it in same directory where JavaStreams.java defined.It will contain names of bands and each line will contain only one band name.
File : bands.txt

Rolling Stones
Lady Gaga
Jackson Browne
Maroon 5
Arijit Singh
Elton John
John Mayer
CCR
Eagles
Pink
Aerosmith
Adele
Taylor Swift
Faye Wong
Bob Seger
ColdPlay
Boston
The Cars
Cheap Trick
Def Leppart
Ed Sheeran
Dire Straits
Train
Tom Petty
Jack Johnson
Jimmy Buffett
public class JavaStreams {
    public static void main(String[] args) throws IOException {

       // 8. Stream rows from text file, sort, filter and print
        Stream bands = Files.lines(Paths.get("bands.txt"));
        bands
            .sorted()
            .filter(x->x.length()>13)
            .forEach(System.out::println);
        bands.close();
   }
}
Output : 
Arijit Singh
Cheap Trick
Def Leppart
Dire Straits
Jack Johnson
Jackson Browne
Jimmy Buffett
Rolling Stones
Taylor Swift

Files.lines will return stream rows, read each line and put it into stream.

We can get stream rows from text file and save it in list :

public class JavaStreams {
    public static void main(String[] args) throws IOException {

       // 9. Stream rows from text file and save to List
        List bands2 = Files.lines(Paths.get("bands.txt"))
                .filter(x->x.contains("ji"))
                .collect(Collectors.toList());
        bands2.forEach(System.out::println);
        System.out.println();
   }
}
Output : Arijit Singh

Collect –  is terminal operation which will save the filtered stream rows to List.

I hope you people enjoyed reading this. Please write your feedback or queries in the comment box.

Thanks 🙂


Viewing all articles
Browse latest Browse all 6

Trending Articles