public class Welcome { public static void main(String[] args) { IntStream values = IntStream.of(-1, -2, -3, -4, 5, -6, -7); IntPredicate positivePred = val -> val > 0; if (values.anyMatch(positivePred)) { int positiveVal = values.filter(positivePred).findAny().getAsInt(); // System.out.println(positiveVal); } } } 1. Program will compile and run perfectly and print 5
2. Program will compile and run perfectly and print nothing
Correct Answer : Get Lastest Questions and Answer : Explanation: As we can see in the code, we are trying to consume the same stream twice. First using anyMatch (It is a termination method) and second with findAny(). Second call with findAny() throw java.lang.IllegalStateException: stream has already been operated upon or closed
Question : You have been given below code, what is the behavior expected? package com.hadoopexam;
import java.util.stream.Stream;
public class Welcome { public static void main(String[] args) { boolean value = Stream.of("Ha", "do", "op", "Ex", "am", ".c", "om") .filter(str -> str.length() > 3) //n1 .peek(System.out::println) .allMatch(str -> str.length() > 5); System.out.println(value); } } 1. Code will give compile time error.
Correct Answer : Get Lastest Questions and Answer : Explanation: As we know that first predicate will not result any output at line n1, hence peek method will not print anything. Next we call allMatch method over the empty stream. Hence, it will return true. Because allMatch() and noneMatch() on empty stream will return true.
Question : You have been given following code, what is the behavior you are expecting? package com.hadoopexam;
import java.util.*;
class Welcome { public static void main(String[] args) { List list = Arrays.asList("Hadoop ", "Exam ", "Quick ", "Techie "); Collections.sort(list, (str1, str2) -> str2.compareTo(str1)); list.forEach(word -> System.out.print(word)); } } 1. Code will give compile time error.
4. Code will run perfectly and print "Exam Hadoop Quick Techie"
Correct Answer : Get Lastest Questions and Answer : Explanation: As we know that Collections.sort() methods second argument should be a Comparator. Hence, we are creating a lambda expression which is a Comparator for the sort method. However, we have provided labda expression such that str2 will be compared with str1. Which will produce result in descending order.