How to use Java Streams

Java 11 Certification Practice Questions

Section: Working with Streams and Lambda expressions

Objective: Implement functional interfaces using lambda expressions, including interfaces from the java.util.function package

For answers to the below questions, please visit http://talks.skilltoz.com/streams-answers

1. What will be the output?
String myStr = "sells";
String joined = myStr
	.chars()
	.distinct()
	.mapToObj(c -> String.valueOf((char) c))
	.peek(System.out::print)
	.sorted()
	.collect(Collectors.joining());
	System.out.println(" "+ joined);

Choices
A. sel els
B. sells ellss
C. sel sel
D. None of the above

2. What will be the output?
public class StreamTest4 {
  public static void main(String[] args) {
    Integer[] a = null;
    Stream<Integer> numStream = a == null ? Stream.empty() : 			
    Stream.of(a);
    printCollection(numStream);
  }
  
  public static void printCollection(Stream<Integer> numStream) {
	numStream.forEach(p -> System.out.print(p));
  }
}

Choices

A) Does not compile
B) Causes NullPointerException
C) No output
D) Prints null

3. What will be the output?
Stream.Builder<String> myStreamBuilder = Stream.builder();
myStreamBuilder.accept("d");
Stream<String> myStream = myStreamBuilder.add("a").add("b").add("c").build();
myStreamBuilder.accept("e");
myStream.forEach(p -> System.out.print(p));

Choices
A) Does not compile
B) Prints “dabce”
C) Prints “dabc”
D) Causes IllegalStateException

4. Given the following array. Which of the following code fragments will run without errors and why?
String[] arr = new String[] { "1", "2", "3" };
Choices
A.   Stream<String> myStream = Arrays.stream(arr);
     myStream.forEach(p -> System.out.print(p));
     Stream<String> myStream1 = Arrays.stream(arr);
     myStream1.forEach(p -> System.out.print(p));
B.   Stream<String> myStream = Arrays.stream(arr);
     myStream.forEach(p -> System.out.print(p));
     myStream.forEach(q -> System.out.print(q));
5. Given the following piece of code.
String purple = "Purple";
List<String> balloons = Arrays.asList("Purple", "Yellow", "Green");

Which of the following pieces of code can be used to check if “Purple” is there in the given list?

Choices

a. hasPurple = balloons.stream().anyMatch(element -> element.contains(purple));
b. hasPurple = balloons.stream().anyMatch(purple::contains);
c. hasPurple = balloons.stream().allMatch(element -> element.contains(purple));
d. hasPurple = balloons.stream().allMatch(purple::contains);

6. What will be the result of running this code?
public class IntermediateTest1 {
 public static void main(String args[]) {
  Stream.of("d2", "a2", "b1", "b3", "c1").filter(s -> 
    s.endsWith("1")).filter(s -> {
       System.out.println("filter: " + s);
       return true;
     });
 }
}

Choices

A. Does not compile
B. Causes exception at runtime
C. Prints
filter: b1
filter: c1
D. Prints nothing

7. What is the result of compiling and running the following code?
Stream<String> myStream = Stream.of("d2", "c2", "c1", "b2", "c3");
Stream<String> numStream = myStream.map((String element) -> 
     element.substring(0, element.length() - 1));
numStream.forEach((String element) -> System.out.println(element));
Stream<String> upperCaseStream = myStream.map((String element) -> 
     element.toUpperCase());
upperCaseStream.forEach((String element) -> 
     System.out.println(element));

Choices
A. Does not compile
B. Causes exception at runtime
C. Prints
D
C
C
B
C
E. Prints
D2
C2
C1
B2
C3

8. Given the code fragment:
1 List<Integer> lst = List.of(1, 2, 3, 4);
2 lst.replaceAll(x -> x + 100);
3 System.out.println(lst);
Which action enables to print the list [101,102,103,104] ?

Choices

A. Replacing line 1, with List lst = List.of(1, 2, 3, 4);
B. Replacing line 2, with lst.replaceAll(x = x + 100);
C. Replacing line 2, with lst.forEach(x -> x + 100);
D. Replacing line 1, with List lst = Arrays.asList(1, 2, 3, 4);

Primitive Streams

9. Which of the following code fragments prints the result as 2.5?

Choices

A. IntStream.range(1, 5).average().ifPresent(System.out::println); 
B. Stream.of(new int[] { 1, 2, 3, 4 }).average().ifPresent(System.out::println);
C. Arrays.stream(new int[] { 1, 2, 3, 4 }).average().ifPresent(System.out::println);
D) Arrays.asList(new int[] { 1, 2, 3, 4 }).average().ifPresent(System.out::println); 
10. Which line when inserted at line no: 6 results in the output of [64]?
     List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8);
     List<Integer> list = numbers.stream()
            .filter(n -> {
                return n % 2 == 0;
           })
           <insert code here>
            .map(n -> {
               return n * n;
            })
           .collect(Collectors.toList());
     System.out.println(list);

Choices

A. skip(3)
B. skip5)
C. limit(3)
D. limit(5)

11. Which piece of code when inserted at line number 5 will cause this code to compile?
List<Integer> integerList = Stream
		.of("12", "1", "14", "10")
		.mapToInt(s -> Integer.parseInt(s))
		.peek((e -> System.out.println("Mapped: " + e)))
		//Insert code here
		.collect(Collectors.toList());
A. .sorted()
B. .peek()
C. .boxed()
D. .average()
12. Which of the below choices can be added after line number 1 for this code to compile and run without errors?
Stream<Integer> numStream = Stream.of(10, 20, 30);
//Insert code here

A.  numStream
     .filter(n -> n > 15)
     .peek(s -> System.out.print(s))
     .forEach(s -> System.out.print(s));
 
B.  long count = numStream
      .map(n -> n + 10)
      .peek(s -> System.out.print(s))
      .count();
 
C.  numStream.map(n -> n + 10)
      .peek(s -> System.out.print(s));
    long count = numStream.count();
 
D.  numStream
      .map(n -> n + 10)
      .peek()
      .forEach(s -> System.out.print(s));
For answers to the above questions, please visit http://talks.skilltoz.com/streams-answers

Leave a Reply

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