OCJP Practice Papers Java Stream API include following topics

  • Develop code to extract data from an object using peek() and map() methods including primitive versions of the map() method
  • Search for data by using search methods of the Stream classes including findFirst,findAny, anyMatch, allMatch, noneMatch
  • Develop code that uses the Optional class
  • Develop code that uses Stream data methods and calculation methods
  • Sort a collection using Stream API
  • Save results to a collection using the collect method and group/partition data usingthe Collectors class
  • Use flatMap() methods in the Stream API

See the complete syllabus for OCJP here

1. Which of the following fills in the blank so that the code outputs one line but uses apoor practice? import java.util.*; public class Cheater { int count = 0; public void sneak(CollectionString coll) { coll.stream().________; } public static void main(String[] args) { Cheater c = new Cheater(); c.sneak(Arrays.asList(“weasel”)); } }
A. peek(System.out::println)
B. peek(System.out::println).findFirst()
C. peek(r - System.out.println(r)).findFirst()
D. peek(r - {count++; System.out.println(r); }).findFirst()

2. Which can fill in the blank to have the code print true? StreamInteger stream = Stream.iterate(1, i i+1); boolean b = stream.____________(i - i 5); System.out.println(b);
A. anyMatch
B. allMatch
C. noneMatch
D. None of the above

3. On a DoubleStream, how many of the methods average(), count(), and sum() return anOptionalDouble?
A. None
B. One
C. Two
D. Three

4. How many of the following can fill in the blank to have the code print 44? StreamString stream = Stream.of("base", "ball"); stream._____________(s - s.length()).forEach(System.out::print); I. map II. mapToInt III. mapToObject
A. None
B. One
C. Two
D. Three

5. What is the result of the following? IntStream s = IntStream.empty(); System.out.print(s.average().getAsDouble());
A. The code prints 0.
B. The code prints 0.0.
C. The code does not compile.
D. The code compiles but throws an exception at runtime.

6. Which of these stream pipeline operations takes a Predicate as a parameter andreturns an Optional?
A. anyMatch()
B. filter()
C. findAny()
D. None of the above

7. What is the result of the following? ListDouble list = new ArrayList(); list.add(5.4); list.add(1.2); OptionalDouble opt = list.stream().sorted().findFirst(); System.out.println(opt.get() + " " + list.get(0));
A. 1.2 1.2
B. 1.2 5.4
C. 5.4 5.4
D. None of the above

8. Fill in the blank so this code prints 8.0. IntStream stream = IntStream.of(6, 10); LongStream longs = stream.mapToLong(i - i); System.out.println(____________);
A. longs.average().get()
B. longs.average().getAsDouble()
C. longs.getAverage().get()
D. longs.getAverage().getAsDouble()

9. How many of these collectors can fill in the blank to make this code compile? StreamCharacter chars = Stream.of( 'o', 'b', 's', 't', 'a', 'c', 'l', 'e'); chars.map(c - c).collect(Collectors.____________ ); I. toArrayList() II. toList() III. toMap()
A. None
B. One
C. Two
D. Three

10. What does the following output? import java.util.*; public class MapOfMaps { public static void main(String[] args) { MapInteger, Integer map = new HashMap(); map.put(9, 3); MapInteger, Integer result = map.stream().map((k,v) (v,k)); System.out.println(result.keySet().iterator().next()); } }
A. 3
B. 9
C. The code does not compile.
D. The code compiles but throws an exception at runtime.

11. Which of the following creates an Optional that returns true when calling opt.isPresent()? I. OptionalString opt = Optional.empty(); II. OptionalString opt = Optional.of(null); III. OptionalString opt = Optional.ofNullable(null);
A. I
B. I and II
C. I and III
D. None of the above

12. What is the output of the following? StreamString s = Stream.of("speak", "bark", "meow", "growl"); BinaryOperatorString merge = (a, b) a; MapInteger, String map = s.collect(toMap(String::length, k k, merge)); System.out.println(map.size() + " " + map.get(4));
A. 2 bark
B. 2 meow
C. 4 bark
D. None of the above

13. What is the output of the following? 1: package reader; 2: import java.util.stream.*; 3: 4: public class Books { 5: public static void main(String[] args) { 6: IntegerStream pages = IntegerStream.of(200, 300); 7: IntegerSummaryStatistics stats = pages.summaryStatistics(); 8: long total = stats.getSum(); 9: long count = stats.getCount(); 10: System.out.println(total + "-" + count); 11: } 12: }
A. 500-0
B. 500-2
C. The code does not compile.
D. The code compiles but throws an exception at runtime.

14. If this method is called with Stream.of("hi"), how many lines are printed? public static void print(StreamString stream) { ConsumerString print = System.out::println; stream.peek(print) .peek(print) .map(s - s) .peek(print) .forEach(print); }
A. Three
B. Four
C. The code compiles but does not output anything.
D. The code does not compile.

15. What is true of the following code? StreamCharacter stream = Stream.of('c', 'b', 'a'); // z1 stream.sorted().findAny().ifPresent(System.out::println); // z2
A. It is guaranteed to print the single character a.
B. It can print any single character of a, b, or c.
C. It does not compile because of line z1.
D. It does not compile because of line z2.

16. Suppose you have a stream pipeline where all the elements are of type String. Which of the following can be passed to the intermediate operation sorted()?
A. (s,t) - s.length() - t.length()
B. String::isEmpty
C. Both of these
D. Neither of these

17. Fill in the blanks so that both methods produce the same output for all inputs. private static void longer(OptionalBoolean opt) { if (opt.____________()) System.out.println("run: " + opt.get()); }p rivate static void shorter(OptionalBoolean opt) { opt.map(x - "run: " + x).____________(System.out::println); }
A. isNotNull, isPresent
B. ifPresent, isPresent
C. isPresent, forEach
D. isPresent, ifPresent

18. What is the output of this code? StreamBoolean bools = Stream.iterate(true, b !b); MapBoolean, ListBoolean map = bools.limit(1) .collect(partitioningBy(b - b)); System.out.println(map);
A. {true=[true]}
B. {false=null, true=[true]}
C. {false=[], true=[true]}
D. None of the above

19. What does the following output? SetString set = new HashSet(); set.add("tire-"); ListString list = new LinkedList(); DequeString queue = new ArrayDeque(); queue.push("wheel-"); Stream.of(set, list, queue) .flatMap(x - x.stream()) .forEach(System.out::print);
A. [tire-][wheel-]
B. tire-wheel-
C. None of the above.
D. The code does not compile.

20. What is the output of the following? StreamString s = Stream.of("over the river", "through the woods", "to grandmother's house we go"); s.filter(n - n.startsWith("t")) .sorted(Comparator::reverseOrder) .findFirst() .ifPresent(System.out::println);
A. over the river
B. through the woods
C. to grandmother's house we go
D. None of the above

21. Which fills in the blank so the code is guaranteed to print 1? StreamInteger stream = Stream.of(1, 2, 3); System.out.println(stream.____________);
A. findAny()
B. first()
C. min()
D. None of the above

22. Which of the following can be the type for x? private static void spot(____________ x) { x.filter(y - ! y.isEmpty()) .map(y - 8) .ifPresent(System.out::println); } I. ListString II. OptionalCollection III. OptionalString IV. StreamCollection
A. I
B. IV
C. II and III
D. II and IV

23. Which can fill in the blank to have the code print true? StreamInteger stream = Stream.iterate(1, i i); boolean b = stream.____________(i - i 5); System.out.println(b);
A. anyMatch
B. allMatch
C. noneMatch
D. None of the above

24. What collector turns the stream at left to the Map at right?
A. grouping()
B. groupingBy()
C. partitioning()
D. partitioningBy()

25. Which fills in the blank for this code to print 667788? IntStream ints = IntStream.empty(); IntStream moreInts = IntStream.of(66, 77, 88); Stream.of(ints, moreInts).____________(x - x).forEach(System.out::print);
A. flatMap
B. flatMapToInt
C. map
D. None of the above

26. Fill in the blank so this code prints 8.0. Note that it must not print OptionalDouble[8.0]. LongStream stream = LongStream.of(6, 10); LongSummaryStatistics stats = stream.summaryStatistics(); System.out.println(____________);
A. stats.avg()
B. stats.average()
C. stats.average().get()
D. stats.getAverage()

27. Which can independently fill in the blank to output No dessert today? import java.util.*; public class Dessert { public static void main(String[] yum) { eatDessert(Optional.of("Cupcake")); } private static void eatDessert(OptionalString opt) { System.out.println(opt.____________); } }
A. get("No dessert today")
B. orElse("No dessert today")
C. orElseGet(() - "No dessert today")
D. None of the above

28. What does the following output? StreamCharacter chars = Stream.generate(() 'a'); chars.filter(c - c 'b') .sorted() .findFirst() .ifPresent(System.out::print);
A. a
B. The code runs successfully without any output.
C. The code enters an infinite loop.
D. The code compiles but throws an exception at runtime.

29. How many of the following can fill in the blank to have the code print the single digit 9? LongStream stream = LongStream.of(9); stream.____________(p - p).forEach(System.out::print); I. mapToDouble II. mapToInt III. mapToLong
A. None
B. One
C. Two
D. Three

30. Suppose you have a stream with one element and the code stream.xxxx.forEach(System.out::println). Filling in xxxx from top to bottom in the table, how many elements can be printed out? xxxx Number elements printed filter() flatMap() map()
A. Zero or one, zero or more, exactly one
B. Zero or one, exactly one, zero or more
C. Zero or one, zero or more, zero or more
D. Exactly one, zero or more, zero or more

31. What is the output of the following? StreamCharacter stream = Stream.of('c', 'b', 'a'); System.out.println(stream.sorted().findFirst());
A. It is guaranteed to print the single character a.
B. It can print any single character of a, b, or c.
C. The code does not compile.
D. None of the above

32. What is the output of the following? public class Compete { public static void main(String[] args) { StreamInteger is = Stream.of(8, 6, 9); ComparatorInteger c = (a, b) a b; is.sort(c).forEach(System.out::print); } }
A. 689
B. 986
C. The code does not compile
D. The code compiles but throws an exception at runtime.

33. What is the result of the following? class Ballot { private String name; private int judgeNumber; private int score; public Ballot(String name, int judgeNumber, int score) { this.name = name; this.judgeNumber = judgeNumber; this.score = score; } // all getters and setters } public class Speaking { public static void main(String[] args) { StreamBallot ballots = Stream.of( new Ballot("Mario", 1, 10), new Ballot("Christina", 1, 8), new Ballot("Mario", 2, 9), new Ballot("Christina", 2, 8) ); MapString, Integer scores = ballots.collect( groupingBy(Ballot::getName, summingInt(Ballot::getScore))); // w1 System.out.println(scores.get("Mario")); } }
A. The code prints 2.
B. The code prints 19.
C. The code does not compile due to line w1.
D. The code does not compile due to a different line.

34. Which can fill in the blank so this code outputs true? import java.util.function.*; import java.util.stream.*; public class HideAndSeek { public static void main(String[] args) { StreamBoolean hide = Stream.of(true, false, true); boolean found = hide.filter(b - b).__________(); System.out.println(found); } }
A. Only anyMatch
B. Only allMatch
C. Both anyMatch and allMatch
D. The code does not compile with any of these options.

35. What does the following output? SetString set = new HashSet(); set.add("tire-"); ListString list = new LinkedList(); DequeString queue = new ArrayDeque(); queue.push("wheel-"); Stream.of(set, list, queue) .flatMap(x - x) .forEach(System.out::print);
A. [tire-][wheel-]
B. tire-wheel-
C. None of the above
D. The code does not compile.

36. When working with a StreamString, which of these types can be returned from the collect() terminal operator by passing arguments to Collectors.groupingBy()? I. MapInteger, ListString II. MapBoolean, HashSetString III. ListString
A. I
B. II
C. I and II
D. I, II, and III

37. Which line can replace line 18 without changing the output of the program? 1: class Runner { 2: private int numberMinutes; 3: public Runner(int n) { 4: numberMinutes = n; 5: } 6: public int getNumberMinutes() { 7: return numberMinutes; 8: } 9: public boolean isFourMinuteMile() { 10: return numberMinutes 4*60; 11: } 12: } 13: public class Marathon { 14: public static void main(String[] args) { 15: StreamRunner runners = Stream.of(new Runner(250), 16: new Runner(600), new Runner(201)); 17: long count = runners 18: .filter(Runner::isFourMinuteMile) 19: .count(); 20: System.out.println(count); 21: } 22: }
A. .map(Runner::isFourMinuteMile)
B. .mapToBool(Runner::isFourMinuteMile) .filter(b - b == true)
C. .mapToBoolean(Runner::isFourMinuteMile) .filter(b - b == true)
D. None of the above

38. Which method is not available on the IntSummaryStatistics class?
A. getCountAsLong()
B. getMax()
C. toString()
D. None of the aboveall three methods are available.

39. Which can fill in the blank so this code outputs Caught it? import java.util.*; public class Catch { public static void main(String[] args) { Optional opt = Optional.empty(); try { apply(opt); } catch (IllegalArgumentException e) { System.out.println("Caught it"); } } private static void apply(OptionalException opt) { opt.__________(IllegalArgumentException::new); } }
A. orElse
B. orElseGet
C. orElseThrow
D. None of the above. The main() method does not compile.

40. A developer tries to rewrite a method that uses flatMap() without using that intermediate operator. Which pair of method calls shows the withoutFlatMap() method is not equivalent to the withFlatMap() method? public static void main(String[] args) { ListString list = new LinkedList(); DequeString queue = new ArrayDeque(); queue.push("all queued up"); queue.push("last"); } private static void withFlatMap(Collection? coll) { Stream.of(coll) .flatMap(x - x.stream()) .forEach(System.out::print); System.out.println(); } private static void withoutFlatMap(Collection? coll) { Stream.of(coll) .filter(x - !x.isEmpty()) .map(x - x) .forEach(System.out::print); System.out.println(); }
A. withFlatMap(list); withoutFlatMap(list);
B. withFlatMap(queue); withoutFlatMap(queue);
C. Both pairs disprove the claim.
D. Neither pair disproves this claim.

OCJP Practice Test, Certification Path, Tips/Tricks

  1. Oracle (OCJP) Java Certification Exam
  2. Java Certification Tips And Tricks
  3. OCJP Practice Papers - Java Basics
  4. OCJP Practice Papers - Operators And Decision Constructs
  5. OCJP Practice Papers-A Advanced Java Class Design
  6. OCJP Practice Papers Creating And Using Arrays
  7. OCJP Practice Papers Using Loop Constructs
  8. OCJP Practice Papers - Generics And Collections
  9. OCJP Practice Papers - Lambda Built-In Functional Interfaces
  10. OCJP Practice Papers Java Class Design
  11. OCJP Practice Papers - Java Stream API
  12. OCJP Practice Papers - Exceptions And Assertions
  13. OCJP Practice Papers - Date/Time API
  14. OCJP Practice Papers - Java I/O Fundamentals
  15. OCJP Practice Papers - Working With Methods And Encapsulation
  16. OCJP Practice Papers - Working With Inheritance
  17. OCJP Practice Papers - Handling Exceptions
  18. OCJP Practice Papers - Selected Classes From Java API
  19. OCJP Practice Papers - Java File I/O Nio.2
  20. OCJP Practice Papers - Java Concurrency