JAVA8 Coding Interview Questions
https://blog.devgenius.io/java-8-coding-and-programming-interview-questions-and-answers-
62512c44f062
1. Given a list of integers, find out all the even numbers that exist in the list using Stream functions
Public class EvenNumber {
Public static void main(String[] args){
List<Integer> list = Arrays.asList(10,20,15,13,26);
list.stream()
.filter(n->n%2==0)
.forEach(System.out::println);
int[] nums= new int[]{10,20,15,13,26};
Map<Boolean, List<Integer>> list1= Arryas.stream(nums).boxed()
.collect(Collectors.partitioningBy(num->num%2==0));
System.out.println(list1);
Notes:
Stream<Integer> java.util.stream.IntStream.boxed()
Returns a Stream consisting of the elements of this stream, each boxed to an Integer.
<Integer> Collector<Integer, ?, Map<Boolean, List<Integer>>>
java.util.stream.Collectors.partitioningBy(Predicate<? super Integer> predicate)
Returns a Collector which partitions the input elements according to a Predicate, and organizes them
into a Map<Boolean, List<T>>. The returned Map always contains mappings for both false and true keys.
There are no guarantees on the type, mutability, serializability, or thread-safety of the Map or List
returned.
// Given a list of integers, find out all the numbers starting with 1 using Stream functions?
public class NumberStartWithOne{
public static void main(String args[]) {
List<Integer> list = Arrays.asList(10,11,9,21,34,38,18,27,60,33);
System.out.println("Numbers starting with 1: ");
list.stream()
.map(s-> s + "") //convert integer to string
.filter(n->n.startsWith("1"))
.forEach(System.out::println);
System.out.println("Numbers starting with 2: ");
list.stream()
.map(String::valueOf) //convert integer to string
.filter(n->n.startsWith("2"))
.forEach(System.out::println);
System.out.println("Numbers starting with 3: ");
list.stream()
.map(s->s.toString()) //convert integer to string
.filter(n->n.startsWith("3"))
.forEach(System.out::println);
Note:
Map->Returns a stream consisting of the results of applying the given function to the elements of this
stream.
Returns a stream consisting of the elements of this stream that match the given predicate.
//3. How to find duplicate elements in a given integers list in java using Stream functions?
public class DuplicteElements{
public static void main(String[] args) {
List<Integer> list =Arrays.asList(1,1,10,9,8,7,8,5,3,4,21,21,30,21,60,63,60);
Set<Integer> set=new HashSet<>();
list.stream()
.filter(n-> !set.add(n))
.forEach(System.out::println);
Note:
Set->A collection that contains no duplicate elements.