Home  >  Java 8

Java 8 Stream: concat, count, sorted and distinct Example

By Arvind Rai, November 19, 2014
On this page we will provide the examples of concat, count, sorted and distinct stream API methods of java 8. concat method is static and count, sorted and distinct methods are called on stream object created by stream() method calling on collection.

Stream.concat

concat() is a static method in stream API. It concats two stream object and returns resulting stream object. In our example we have two lists which are converted into stream and then concatenated.
ConcatDemo.java
package com.concretepage.util.stream;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
public class ConcatDemo {
    public static void main(String[] args) {
        List<String> list1 = Arrays.asList("A1","A2","A3");
        List<String> list2 = Arrays.asList("B1","B2","B3");
        Stream<String> resStream = Stream.concat(list1.stream(), list2.stream());
        resStream.forEach(s->System.out.println(s));
    }
} 
Find the output.
A1
A2
A3
B1
B2
B3

Stream.count

count() method in stream API just counts the elements in stream object. It returns long value. In our example we have a list and we convert it into stream then apply count() method on it.
CountDemo.java
package com.concretepage.util.stream;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
public class CountDemo {
    public static void main(String[] args) {
        List<String> list = Arrays.asList("AA","AB","CC");
        Predicate<String> predicate = s-> s.startsWith("A");
        long l= list.stream().filter(predicate).count();
        System.out.println("Number of Matching Element:"+l);
    }
} 
Find the output.
Number of Matching Element:2 

Stream.sorted

sorted() method in stream API sorts the elements of stream on the basis of natural order. We can also pass our comparator object to get custom sorting.
SortedDemo.java
package com.concretepage.util.stream;
import java.util.Arrays;
import java.util.List;
public class SortedDemo {
    public static void main(String[] args) {
         List<String> list = Arrays.asList("DC","CD","AD");
         list.stream().sorted().forEach(s->System.out.println(s));
    }
} 
Find the output.
AD
CD
DC 

Stream.distinct

distinct() method in stream API returns stream with distinct element. Distinct element is decided by equal method of Object class.
DistinctDemo.java
package com.concretepage.util.stream;
import java.util.Arrays;
import java.util.List;
public class DistinctDemo {
    public static void main(String[] args) {
        List<String> list = Arrays.asList("AA","AA","BB");
        long l = list.stream().distinct().count();
        System.out.println("Number of distinct element:"+l);
    }
} 
Find the output.
Number of distinct element:2 
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS


©2018 concretepage.com | Privacy Policy | Contact Us