Java8 | Stream API

Stream Source

Stream<String> stream1 = Stream.empty();
Stream<Integer> stream2 = Stream.of(1);
Stream<Integer> stream3 = Stream.of(1, 2, 3, 4, 5, 6, 7);
List<String> list = Arrays.asList("a", "b", "c");
Stream<String> fromList = list.stream();
Stream<Double> randoms = Stream.generate(Math::random).limit(5);

Stream<Integer> oddNumbers = Stream.iterate(1, n -> n + 2).limit(5);
Arrays.stream(Object.class.getMethods()) // source
.map(Method::getName) // intermediate op
.distinct() // intermediate op
.forEach(System.out::println); // terminal operation
IntStream.range(1, 10).forEach(System.out::println);

IntStream.rangeClosed(1, 5)
.map(e -> e * 2)
.forEach(System.out::println);
IntStream.iterate(10, i -> i + 5)
.limit(6)
.forEach(System.out::println);
// public static IntStream stream(int[] array) {
IntStream intStream = Arrays.stream(new int[] { 1, 2, 3, 4, 5 });

// public static <T> Stream<T> stream(T[] array) {
Stream<Integer> integerStream = Arrays.stream(new Integer[] { 1, 2, 3, 4, 5 });
//public static Pattern compile(String regex)
// public Stream<String> splitAsStream(final CharSequence input)
Pattern.compile(" ")
.splitAsStream("java 8 streams")
.forEach(System.out::println);

Intermediate Operations

Stream<T> peek(Consumer<? super T> action);
Stream.of("one", "two", "three", "four")
.filter(e -> e.length() > 3)
.peek(e -> System.out.println("Filtered value: " + e))
.map(String::toUpperCase)
.peek(e -> System.out.println("Mapped value: " + e));
//this code doesn't give any outputs,
//we should add this -> .collect(Collectors.toList()); <-
Stream.of(1, 2, 3, 4, 5)
.peek(i -> System.out.printf("%d ", i))
.map(i -> i * i)
.peek(i -> System.out.printf("%d ", i)).count();
//if we didn't add the .count(), we wouldn't' see any outputs
Stream<T> filter(Predicate<? super T> predicate);
IntStream.rangeClosed(0,10)
.filter(i -> (i % 2 == 0))
.map(i -> i*3)
.forEach(System.out::println);
Stream.of("Hasan", "Kadir", "", "Java")
.filter(name -> !name.isEmpty())
.forEach(System.out::println);
Stream<T> distinct();
Stream.of("Java", "Java", "Java8", "JAva")
.distinct()
.forEach(System.out::println);
Stream<Integer> s = Stream.iterate(10, n -> n + 2);

s.skip(3).limit(2).forEach(System.out::println); //16, 18
Stream<String> s = Stream.of("hasan", "kadir", "demircan");
s.map(String::length).forEach(System.out::print); // 558
List<String> numbers = Arrays.asList("1", "2", "3", "4", "5", "6");
List<Integer> even = numbers.stream()
.map(Integer::valueOf)
.filter(number -> number % 2 == 0)
.collect(Collectors.toList());
List<Match> matchList = Arrays.asList(
new Match("FootballMatch", 11),
new Match("BasketballMatch", 7),
new Match("Soccer", 7),
new Match("Tennis", 2)
);

Optional<String> matchName = matchList.stream()
.map(Match::getName)
.filter(name -> name.endsWith("Match"))
.sorted()
.findFirst();
System.out.println("Result: " + matchName.orElse("match no found"));
<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper);
flatMap() = Flattening + map()
String[] string = "you never know what you have until you clean your room".split(" ");
Arrays.stream(string)
.map(word -> word.split(""))
.distinct()
.forEach(System.out::println);
//This code prints gibberish like this:Ljava.lang.String;@5f184fc6[Ljava.lang.String;@3feba861[Ljava.lang.String;@5b480cf9[
String[] string = "you never know what you have until you clean your room".split(" ");
Arrays.stream(string)
.flatMap(word -> Arrays.stream(word.split("")))
.distinct()
.forEach(System.out::println);
//This code prints gibberish like this:
y
o
u
n
(etc..)
List<List<Integer>> intsOfInts = Arrays.asList(Arrays.asList(1, 3, 5), Arrays.asList(2, 4));

intsOfInts.stream()
.flatMap(Collection::stream)
.sorted()
.map(i -> i * i)
.forEach(System.out::println);
flatMap Example Schema
 Stream<T> sorted()
Stream<T> sorted(Comparator<? super T> comparator)
Stream<String> s = Stream.of("brown-", "bear-", "bee-");
s.sorted().forEach(System.out::print);
// bear-bee-brown-
Stream.generate(() -> "Elsa")
.filter(n -> n.length() == 4)
.sorted()
.limit(2)
.forEach(System.out::println);
Stream.generate(() -> "Elsa")
.filter(n -> n.length() == 4)
.limit(2)
.sorted()
.forEach(System.out::println);

Terminal Operation

Stream<String> s1 = Stream.of("k1", "k2", "k3");
long countElement = s1.count();
System.out.println(countElement);
Stream<String> stream1 = Stream.of("monkey", "ape", "bonobo");
Stream<String> stream2 = Stream.of("monkey", "ape", "bonobo");

Comparator<String> comp = Comparator.comparingInt(String::length);

Optional<String> min = stream1.min(comp);
Optional<String> max = stream2.max(comp);

System.out.println(min);
System.out.println(max);
String[] string = "you never know what you have until you clean your room".split(" ");
String[] string2 = "you never know what you have until you clean your room".split(" ");
String[] string3 = "you never know what you have until you clean your room".split(" ");

System.out.println(Arrays.stream(string).min(String::compareTo).get());
System.out.println(Arrays.stream(string2).max(String::compareTo).get());

Comparator<String> lengthCompare = Comparator.comparingInt(String::length);
System.out.println(Arrays.stream(string3).min(lengthCompare).get());
Stream<String> s = Stream.of("monkey", "gorilla", "bonobo");
Stream<String> infinite = Stream.generate(() -> "chimp");

s.findAny().ifPresent(System.out::println); // monkey

infinite.findAny().ifPresent(System.out::println); // chimp
// DoubleStream filter(DoublePredicate predicate);
OptionalDouble temperature = DoubleStream.of(-10.1, -5.4, 6.0, -3.4, 8.9, 2.2)
.filter(temp -> temp > 0)
.findFirst();

// DoubleStream filter(DoublePredicate predicate);
OptionalDouble temperature2 = DoubleStream.of(-10.1, -5.4, 6.0, -3.4, 8.9, 2.2)
.filter(temp -> temp > 0)
.findAny();

System.out.println(temperature);
System.out.println(temperature2);
List<String> list = Arrays.asList("monkey", "2", "chimp");

Stream<String> infinite = Stream.generate(() -> "chimp");
Stream<String> infinite2 = Stream.generate(() -> "chimp");

Predicate<String> pred = x -> Character.isLetter(x.charAt(0));

System.out.println(list.stream().anyMatch(pred)); // true
System.out.println(list.stream().allMatch(pred)); // false
System.out.println(list.stream().noneMatch(pred));// false

// infinitive
System.out.println(infinite.anyMatch(pred)); // true
// System.out.println(infinite.allMatch(pred)); // true -> endless loop

System.out.println(infinite2.noneMatch(pred)); // false
void forEach(Consumer<? super T> action);
Stream<String> s = Stream.of("Monkey", "Gorilla", "Bonobo");
s.forEach(System.out::print); // MonkeyGorillaBonobo
// Consumer
// void accept(T t);

List<String> list = new ArrayList<>();
s.forEach((str) ->
{
String sUpper = str.toUpperCase();
list.add(sUpper);
});
 T reduce(T identity, BinaryOperator<T> accumulator);
Optional<T> reduce(BinaryOperator<T> accumulator);
Stream<Integer> stream = Stream.of(3, 5, 6);
Stream<Integer> stream2 = Stream.of(3, 5, 6);

// T reduce(T identity, BinaryOperator<T> accumulator);
System.out.println(stream.reduce(10, (a, b) -> a * b));
//Sout: 900

// Optional<T> reduce(BinaryOperator<T> accumulator);
System.out.println(stream2.reduce((a, b) -> a * b));
//Sout: 900Optional[90]
Stream<String> stream = Stream.of("w1", "o2", "l3", "f4");
String word = stream.reduce("X", String::concat);
System.out.println(word); // Xw1o2l3f4
Stream<String> stream2 = Stream.of("w", "o", "l", "f");
String word2 = stream2.reduce("", (s, c) -> s + c +"--");
System.out.println(word2); //w--o--l--f--
<R,A> R collect(Collector<? super T, A,R> collector)
String frenchCounting = "un:deux:trois:quatre";
List<String> gmailList = Pattern.compile(":")
.splitAsStream(frenchCounting)
.collect(Collectors.toList());
//[un, deux, trois, quatre]
String[] roseQuote = "a rose is a rose is a rose".split(" ");
Set<String> words = Arrays.stream(roseQuote).collect(Collectors.toSet());
Map<String, Integer> nameLength = Stream.of("Arnold", "Alois", "Schwarzenegger")
.collect(Collectors.toMap(name -> name, String::length));
Stream<String> stream = Stream.of("w", "o", "l", "f");
StringBuilder word = stream.collect(StringBuilder::new, StringBuilder::append, StringBuilder::append);
Stream<String> stream = Stream.of("w", "o", "l", "f");
TreeSet<String> set = stream.collect(Collectors.toCollection(TreeSet::new));

--

--

--

Java Developer @XPoint-Tech

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

UniDexBot X AMALoversClub AMA

Word Clouds for the Classroom by Acadly

A package for request

ActiveModelSerializer 【Rails】

What technologies do I need to learn to become a full-stack web developer

All About Competitive Coding

All About Competitive coding image description

Creatives vs. Evolutionists

[Leet Code] Count Items Matching a Rule

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Hasan Kadir Demircan

Hasan Kadir Demircan

Java Developer @XPoint-Tech

More from Medium

Spring Boot Embedded Tomcat getNextJarEntry

Spring boot Starter Project In STS

Java — Environment Setup

How to handle Constraint violation exception using ControllerAdvice in Spring boot