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)");         ...