x Java Java 8 JUnit JSON
  • XML
  • JDBC Spring Boot Microservices React Contact Us

    Java 8 Collectors examples

    1. Java 8 Collectors Joining example

    a) Below example shows how to append list of characters Stream using without any delimiter.

    // Stream Collectors Joining example   
    package java8;
    
    import java.util.stream.Collectors;
    import java.util.stream.Stream;
    
    public class CollectorsJoiningExample {
    
        public static void main(String[] args) {
            char[] ch = { 'Y', 'o', 'u', ' ', 'o', 'w', 'n', ' ', 'y', 'o', 'u', 'r', ' ',
                        'd', 'e', 's', 't', 'i', 'n', 'y'};
            
            String str = Stream.of(ch) 
                            .map(c -> new String(c)) 
                            .collect(Collectors.joining()); 
            System.out.println(str);
        }
    }       

    Output :

    You own your destiny    

    b) Below example shows how to append list of Ball names obtained from Stream using ',' delimiter.

    // Stream Collectors Joining example using delimiter
    package java8;
    
    import java.util.Arrays;
    import java.util.List;
    import java.util.stream.Collectors;
    
    public class CollectorsJoiningExample {
    
        public static void main(String[] args) {
            Ball tennis = new Ball("tennis", 1, "green");
            Ball footBall = new Ball("football", 2, "white");
            Ball basketBall = new Ball("basketBall", 3, "orange");
            Ball volleyBall = new Ball("volleyBall", 4, "orange");
            
            List<Ball> balls = Arrays.asList(tennis, footBall, basketBall, volleyBall);
            
            String ballNames = balls.stream()
                    .filter(ball -> ball.getSize() > 1)
                    .map(Ball::getName)
                    .collect(Collectors.joining(","));
            System.out.println("Name of balls greater than size 1 :: " + ballNames);
        }
    }       

    Output :

    Name of balls greater than size 1 :: football,basketBall,volleyBall   

    c) Below example shows how to append list of Ball names obtained from Stream using ',' delimiter, '->' as prefix, and '.' as suffix.

    // Stream Collectors Joining example using delimiter, prefix, and suffix    
    package java8;
    
    import java.util.Arrays;
    import java.util.List;
    import java.util.stream.Collectors;
    
    public class CollectorsJoiningExample {
    
        public static void main(String[] args) {
            Ball tennis = new Ball("tennis", 1, "green");
            Ball footBall = new Ball("football", 2, "white");
            Ball basketBall = new Ball("basketBall", 3, "orange");
            Ball volleyBall = new Ball("volleyBall", 4, "orange");
            
            List<Ball> balls = Arrays.asList(tennis, footBall, basketBall, volleyBall);
            
            String ballNames = balls.stream()
                    .filter(ball -> ball.getSize() > 1)
                    .map(Ball::getName)
                    .collect(Collectors.joining(",", "-> ", "."));
            System.out.println("Name of balls greater than size 1 :: " + ballNames);
        }
    }       

    Output :

    Name of balls greater than size 1 -> football,basketBall,volleyBall.   

    2. Java 8 Collectors minBy(), maxBy() example

    minBy() & maxBy() methods use a Comparator to compare the elements from the stream they are being collected and return a Collector.

    a) Below example shows how to use minBy() & maxBy() on a stream.

    // Stream Collectors minBy & maxBy() example   
    package java8;
    
    import java.util.Optional;
    import java.util.stream.Collectors;
    import java.util.stream.Stream;
    
    public class CollectorsMinByExample {
    
        public static void main(String[] args) {
            Stream<String> stream = Stream.of("Harry", "Alan", "Tom", "John");
            Optional<String> op = stream.collect(Collectors.minBy(String::compareTo));
            if (op.isPresent()) {
               System.out.println(op.get());
            } else {
               System.out.println("Nothing!");
            }
             
            stream = Stream.of("Harry", "Alan", "Tom", "John"); 
            op = stream.collect(Collectors.maxBy(String::compareTo));
            if (op.isPresent()) {
               System.out.println(op.get());
            } else {
               System.out.println("Nothing!");
            }
        }
    }       

    Output :

    Alan   
    Tom

    b) Another minBy() & maxBy() example with custom Comparator.

    // Stream Collectors minBy & maxBy() example   
    package java8;
    
    import java.util.Arrays;
    import java.util.List;
    import java.util.Optional;
    import java.util.stream.Collectors; 
    
    public class CollectorsMinByExample {
    
        public static void main(String[] args) {
             Ball tennis = new Ball("tennis", 1, "green");
             Ball footBall = new Ball("football", 2, "white");
             Ball basketBall = new Ball("basketBall", 3, "orange");
             Ball volleyBall = new Ball("volleyBall", 4, "orange");
             
             List<Ball> balls = Arrays.asList(tennis, footBall, basketBall, volleyBall);
             Optional<Ball> ball = balls.stream().collect(Collectors.minBy((b1, b2)
                -> b1.getSize() - b2. getSize()));
             if (ball.isPresent()) {
                System.out.println("Smallest ball :: " + ball);
             } else {
                System.out.println("Not found!");
             }
             
             ball = balls.stream().collect(Collectors.maxBy((b1, b2) -> b1.getSize() - b2. getSize()));
             if (ball.isPresent()) {
                System.out.println("Biggest ball :: " + ball);
             } else {
                System.out.println("Not found!");
             }
        }
    }
    
    class Ball {
    
        private String name;
        private int size;
        private String color;
    
        public Ball(String name, int size, String color) {
            this.name = name;
            this.size = size;
            this.color = color;
        }
    
        public String getName() {
            return name;
        }
    
        public int getSize() {
            return size;
        }
    
        public String getColor() {
            return color;
        }
    
        @Override
        public String toString() {
            return "Ball [name=" + name + ", size=" + size + ", color=" + color + "]";
        }
    
    }       

    Output :

    Smallest ball :: Optional[Ball [name=tennis, size=1, color=green]]
    Biggest ball :: Optional[Ball [name=volleyBall, size=4, color=orange]]

    References :

    Oracle Docs Collectors joining()

    Oracle Docs Collectors
    Comments

    Leave a Reply

    Your email address will not be published. Required fields are marked *











    Share This