Posts

Collectors Multilevel grouping

public class CollectorsGroupingFlight { public static void main(String[] args) { List<Animal> animals = Arrays.asList(                                new Animal("Tiger", "Wild", "Small"), new Animal("Cow", "Domestic", "Large"), new Animal("Lion", "Wild", "Large"), new Animal("Goat", "Domestic", "Small"), new Animal("Dog", "Domestic", "Small")); Map<String, Map<String, List<Animal>>> result = animals .stream() .collect(groupingBy(Animal::getType,  groupingBy(Animal::getSize))); System.out.println("Result: "+result); } } Output: Result: { Wild={ Small=[Animal [name=Tiger, type=Wild, size=Small]],  Large=[Animal [name=Lion, type=Wild, size=Large]] },  Domestic={ Small=[  Animal [name=Goat, type=Domestic, size=Small],  Animal [name=Dog, typ...

Collectors.groupingBy example

import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class CollectorsGroupingFlight { public static void main(String[] args) { List<Animal> animals = Arrays.asList( new Animal("Tiger","Wild"), new Animal("Cow","Domestic"), new Animal("Lion","Wild"), new Animal("Goat","Domestic"), new Animal("Dog","Wild-Domestic") ); Map<String, List<Animal>> result = animals .stream() .collect(Collectors.groupingBy(Animal::getType)); System.out.println("Result: "+result); } } Output: Result: { Wild-Domestic=[Animal [name=Dog, type=Wild-Domestic]], Wild=[Animal [name=Tiger, type=Wild], Animal [name=Lion, type=Wild]],  Domestic=[Animal [name=Cow, type=Domestic], Animal [name=Goat, type=Domestic]] } Explanation: The result produces the ma...

Collectors.reducing for joining Strings

import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class CollectorReduceFlight { public static void main(String[] dataBag) { List<Person> persons = Arrays.asList( new Person("raj"), new Person("rose"), new Person("jack") ); String names = persons .stream() .map(Person::getName) .collect(Collectors.reducing((s1, s2) ->s1+s2)) .get(); System.out.println("1) Names: "+ names); String temps = persons.stream() .collect( Collectors.reducing(  "2) Names: ", Person::getName,  (s1, s2) -> s1 + s2 )); System.out.println(temps); } } Output: Names: rajrosejack Names: rajrosejack Explanation: Collectors.reducing((s1, s2) ->s1+s2):   Takes name of each person object in String stream  and then reducing the resulting string stream using a String accumulator and the appends to it the name...

Collectors.joining example

import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; class Person{ private String name; Person(String name){ this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } } public class CollectorJoiningFlight { public static void main(String[] dataBag) { Stream<String> strings = Stream.of("Vikram","Ashok","Pratap"); String strs = strings.collect(Collectors.joining(",")); System.out.println("Joined String: "+strs); List<Person> persons= Arrays.asList( new Person("raj"), new Person("rose"), new Person("jack") ); String names =   persons .stream() .map(Person::getName) .collect(Collectors.joining(",")); System.out.println("Names: "+names); } } Output: Joine...

Collectors: maxBy MinBy averagingInt summarizingDouble with Example

import java.util.Comparator; import java.util.DoubleSummaryStatistics; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; class User { private int cash; private String name; public User(int cash, String name) { this.cash = cash; this.name = name; } public int getCash() { return cash; } public void setCash(int cash) { this.cash = cash; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "User [cash=" + cash + ", name=" + name + "]"; } } public class CollectorFindMaxFlight { public static void main(String[] args) { Stream<User> usersStream = getUsersStream(); Comparator<User> userComparator = Comparator.comparingInt(User::getCash); Optional<User> maxCashUser = usersStream.collect(Collectors.maxBy(userComparator)); maxCash...

Collectors.counting to count total elements

import java.util.stream.Collectors; import java.util.stream.Stream; public class CollectorCountFlight { public static void main(String[] args) { long totalNumbers = Stream.of(1,2,3,4,5,6,7,8,9).count(); System.out.println("1) Total Numbers: "+totalNumbers); Stream<Integer> numStream = Stream.of(1,3,4,5,6,7,45,6,9); long totalNums = numStream.collect(Collectors.counting()); System.out.println("2) Total Numbers "+totalNums); } } Output: 1) Total Numbers: 9 2) Total Numbers: 9 Explanation: You can count total elements .count() method on the stream or using the Collectors.counting() public static <T> Collector<T, ?, Long> counting(): Returns a Collector accepting elements of type T that counts the number of input elements in the Stream.  If no elements are present, the result is 0. The counted value is returned in a long.Long type.

IntStream examples

import java.util.stream.IntStream; public class RangeFlight {     public static void main(String[] args) {         IntStream rangeStream = IntStream.range(1, 10);         /*.range(1, 10) means 1 to 9 */         System.out.println("IntStream.range(1, 10)");         rangeStream.forEach(System.out::print);                System.out.println("\n\nIntStream.rangeClosed(1,  10)");         IntStream rangeClosedStream = IntStream.rangeClosed(1,  10);         /*.range(1, 10) means 1 to 10 */         rangeClosedStream.forEach(System.out::print);                System.out.println("\n\nIntStream.iterate(0, n->n+2)");         ...

Stateless vs Statefull Operations

  map and filter takes elements from the stream and it provides the resultant stream with zero or more elements. There operation doesn't need to cache the state or elements. Once the operation done on any element it doesn't need to cache its state for performing operation next element. So, these map and filter are stateless operations. While reduce, sort and distinct all such operation required to cache the state of elements because to perform such operation it needs to have the previous state of the operation. So, these reduce, distinct and sort operations are state full operations.

Stream complex examples like Queries

import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; class Client { private final String name; private final String country; public Client(String n, String c) { this.name = n; this.country = c; } public String getName() { return this.name; } public String getCountry() { return this.country; } public String toString() { return "Client:" + this.name + " in " + this.country; } } class Balance { private final Client client; private final int year; private final int amount; public Balance(Client client, int year, int amount) { this.client = client; this.year = year; this.amount = amount; } public Client getClient() { return this.client; } public int getYear() { return this.year; } public int getAmount() { return this.amount; } public String toString() { return "{" + this.client + ", " + "...

mapToInt() mapToLong() and mapToDouble() example

import java.util.Arrays; import java.util.List; import java.util.OptionalDouble; public class MapToIntLongDoubleFlight { public static void main(String[] args) { List<Integer> numbers = Arrays.asList(1,2,3,4,5,6); int total = numbers .stream() .mapToInt(num->num) .sum(); System.out.println("Total: "+total); OptionalInt min = numbers .stream() . mapToInt (num->num) . min (); System.out.println("Smallest Value: "+min.getAsInt()); OptionalInt max = numbers .stream() . mapToInt (num->num) . max (); System.out.println("Largest Value: "+max.getAsInt()); OptionalDouble average =  numbers .stream() .mapToDouble(num->num) .average(); System.out.println("Average: "+average.getAsDouble()); long totalLong = numbers .stream() .mapToLong(num->num*10000) .sum(); System.out.println("Total Long: "+totalLong); } } Outpu...

reduce() to find min and max

import java.util.Arrays; import java.util.List; import java.util.Optional; public class MaxMinReduceFlight { public static void main(String[] args) { List<Integer> nums = Arrays.asList(11,2,3,4,5,6,7); int max = nums.stream().reduce(0,Integer::max); Optional<Integer> resultMin = nums.stream().reduce(Integer::min); System.out.println("max="+max); System.out.println("min="+resultMin.get()); } } Output: max=11 min=2 Explanation: Integer::max: This method reference will be used to find max value. Integer::min:  This method reference will be used to find min value. for finding minimum value we have taken Optional to get the result because if we will take  initial value 0 then it will give us 0 as a resulted minimum value.

reduce() example

import java.util.Arrays; import java.util.List; public class ReduceFlight { public static void main(String[] args) { List<Integer> nums = Arrays.asList(1,2,3,4,5,6,7); int sum = nums.stream() . reduce ( 0, (n1,n2)->n1+n2 ) ; System.out.println("Sum="+sum);  } } Output: Sum=28 Explanation: reduce is used to convert all values of stream into a single element. It means it is used to reduce stream. reduce ( 0, (n1,n2)->n1+n2 ): it takes two arguments 1st argument is an initial value. 2nd argument is BinaryOperator<T>. It takes two elements in argument and return new element. int sum = numbers.stream().reduce(0, Integer::sum); you can also use method reference to find sum of all elements of stream. int product = nums.stream().reduce(1, (n1,n2)->n1+n2); above is another line of code to find product of the numbers in list. Optional<Integer> sum =  numbers.stream().reduce((n1, n2) -> (n1 + n2)); Above is another line...

findAny() isPresent() and ifPresent() example

import java.util.Arrays; import java.util.List; import java.util.Optional; public class FinyAnyIsPresentIfPresentFlight { public static void main(String[] args) { List<Integer> nums = Arrays.asList(1,2,3,4,5,6,7); Optional<Integer> result = nums .stream() .filter(num->num%2==0) . findAny (); System.out.println("isPresent:"+ result.isPresent() ); System.out.println("resultVal: "+ result.get() ); nums.stream() .filter(num->num%2==0) .findAny() . ifPresent (val->System.out.println("ifPresent: "+val)); } } Output: isPresent:true resultVal: 2 ifPresent: 2 Explanation: findAny(): It find any element from the stream which match the given filter condition. isPresent() : In result optional if the resulted value is available then it will give true else false . result.get(): It returned the found element or it will give NoSuchElementException  ifPresent(): The lamda expr...

allMatch anyMatch and noneMatch

import java.util.Arrays; import java.util.List; public class MatchFlight { public static void main(String[] args) { List<Integer> nums = Arrays.asList(1,2,3,4,5,6,7); boolean allPositive = nums.stream(). allMatch (num->num>0); System.out.println("allPositive: "+allPositive); boolean anyEvenAvailable = nums.stream() . anyMatch (num->num%2==0); System.out.println("anyEvenAvailable: "+anyEvenAvailable); boolean noneNegative = nums.stream(). noneMatch (num->num<0); System.out.println("noneNegative: "+noneNegative); } } Output: allPositive: true anyEvenAvailable: true noneNegative: true Exaplanation: allMatch : It checks all for the elements in the stream match the provided filter condition. anyMatch: It checks any element in the stream match the provided filter condition. noneMatch: It check none element in the stream match the provided filter condition.

Useful tools for Java Developers

Checkstyle: It is a open source and free code analysis tool. It is used in development to check Java code conforms to the coding standards you have established.  It automates the essential but boring task about to check Java code.  It is one of the most popular tools to automate the java code review process. PMD: PMD is a static code analysis tool that is capable to automatically detect a wide range of potential bugs and unsafe or non-optimized code.  It examines Java source code and looks for potential problems such as possible bugs, dead code, suboptimal code, overcomplicated expressions, and duplicated code. Whereas other tools, such as Checkstyle, can verify whether coding conventions and standards are respected, PMD focuses more on preemptive defect detection. FindBugs: FindBugs is an open source Java code quality tool similar in some ways to Checkstyle and PMD, but with a quite different focus. FindBugs doesn’t concern the formatting or coding stan...

flatMap() example

Example: import java.util.Arrays; import java.util.List; public class FlatMapFlight {     public static void main(String[] args) {         System.out.println("main() [Start]");         List<String> words = Arrays.asList("Hello","Good","Morning");                 words         .stream()         .map(word->word.split(""))         .flatMap(Arrays::stream)         .forEach(System.out::println);                 System.out.println("main() [End]");     } } Ouput: main() [Start] H e l l o G o o d M o r n i n g main() [End] Explanation:   . map(word->word.split("")) : filter takes the lamda expression as an argument.  It takes a lam...

skip() example

Example: import java.util.Arrays; import java.util.List; public class SkipFlight {     public static void main(String[] args) {         System.out.println("main() [Start]");        List<Integer> numbers = Arrays.asList(6,10, 20, 10, 3, 2, 4, 6, 9);                 numbers         . stream()         .filter(num->num%2==0)         .skip(2)         .forEach(System.out::println);                 System.out.println("main() [End]");     } } Ouput: main() [Start] 20 10 2 4 6 main() [End] Explanation:   .filter(num->num%2==0) : filter takes the lamda expression as an argument.  It takes a lamda expression having functional interface havi...

limit() example

Example: import java.util.Arrays; import java.util.List; public class LimitFlight {     public static void main(String[] args) {         System.out.println("main() [Start]");       List<Integer> numbers = Arrays.asList(6,10, 20, 10, 3, 3, 2,                                                                         4,6,9,8,9,8,9);                 numbers         . stream()         .filter(num->num%2==0)         .di...

distinct() Example

Example: import java.util.Arrays; import java.util.List; public class DistinctFlight {     public static void main(String[] args) {         System.out.println("main() [Start]");         List<Integer> numbers = Arrays.asList(6,10, 20, 10, 3, 3, 2, 4,6);                 numbers         . stream()         .filter(num->num%2==0)         .distinct()         .forEach(System.out::println);                 System.out.println("main() [End]");     } } Ouput: main() [Start] 6 10 20 2 4 main() [End] Explanation:   .filter(num->num%2==0) : filter takes the lamda expression as an argument.  It takes a lamda expression having functional...

Find odd even Numbers using Streams

       List<Integer> numbers = Arrays.asList(1,3,4,5,6,7,8); List<Integer> evenNumbers =  numbers.stream().filter((num)->num%2==0).collect(Collectors.toList());System.out.println(evenNumbers);          List<Integer> oddNumbers = numbers.stream().filter((num)->num%2!=0).collect(Collectors.toList());System.out.println(oddNumbers);