Using a Local Record for Readability

Sometimes there is something we really want to put in our cert book that doesn’t fit. You can only have so many case studies/real world scenarios after all. I rescued this from the trash heap and made this blog post./

Suppose we want to count the number of names that have both a first and last name beginning with E. We want to call the method as:

var names = List.of("Sarah Smith", "Eve Edwards");
System.out.println(local.countNamesStartingWithEs(names));

We can read this with streams:

public long countNamesStartingWithEs(List<String> names) {
   return names.stream()
      .map(t -> t.split(" "))
      .filter(a -> a[0].startsWith("E"))
      .filter(a -> a[1].startsWith("E"))
      .count();
}

The code works. However, it has array positions sprinkled throughout. This requires you to keep remembering the format. We can refactor using a local record:

public long countNamesStartingWithEsWithRecords(List<String> names) {
   record Name(String first, String last) {}

   return names.stream()
      .map(t -> t.split(" "))
      .map(t -> new Name(t[0], t[1]))
      .filter(n -> n.first().startsWith("E"))
      .filter(n -> n.last().startsWith("E"))
      .count();
    }

The record lets us give the fields names so we can reference them as n.first() and n.last(). The only place that has to know about the order is the call record constructor. For such a simple example, the approaches are similar. For longer and more complex pipelines, the local record approach can make the code easier to read.

[2019 oracle code one] exploring collectors

Exploring Collectors

Speakers: Venkat Subramaniam

For more blog posts, see The Oracle Code One table of contents


General

  • Common operations; filter, map, reduce
  • Filter – like a coin sorter. Will let some values through and discard others
  • Reduce – go from a stream to a non stream
  • Collect is a reduce operation
  • Functions should be pure – doesn’t change anything *and* doesn’t depend on anything that could change

Collectors – concepts

  • Don’t call add() in a forEach. Should be using a Collector
  • Can’t parallelize code when have shared mutability (ex: add() in forEach)
  • Can’t say “the code worked”. Can say “the code behaved”
  • If use ConcurrentList, it’s a ticking time bomb for when someone changes the list type.
  • Should write collect(Collectors.toList()) or collect(toList()). Already handles concurrency (when running with a parallel stream)
  • Venkat prefers using Collectors as a static import and just calling toList()
  • Collectors are recursive data structures. The second parameter is another Collector
  • Often need to chain collectors to do what want.
  • Ok to write code “the long way” and then refactor once have passing tests

Collectors – Code

  • Java 10+: toUnmodifiableList() – immutable list
  • partitioningBy – when need both the matching and non matching results. Avoids needing two passes of data to get result.
  • joining(“, “) – comma separated
  • groupingBy(Person::getName) – create map with key as name and value as list of Person objects. Conceptualize as buckets. Put items in bucket by key
  • groupingBy(Person::getName, mapping(Person::getAge, toList())) – map after group. Perform mapping right before throw data into bucket.
  • groupingBy(Person::getName, counting()) – value is # matching values
  • groupingBy(Person::getName, collectingAndThen(counting(), Long::intValue)) – transform the result of a collector to a different type

My take

I like that Venkat talked about how to write code “the long way” to explain the power of collectors. This was a good review. And good motivation as we update our OCP book (I have the streams chapter). I like the bucket analogy for groupingBy(). I didn’t know about collectingAndThen() The 45 minutes flew!

My Experience taking the new Java SE 11 Programmer II 1Z0-816 Exam

Update (11/05/2020): Read The 1Z0-819 Exam page to learn how you can easily our Java 11 Study Guides to prepare for Oracle’s 1Z0-819 Exam, as well as the 1Z0-817 Upgrade Exam.

Back in March, I took the new Java SE 11 Programmer I 1Z0-815 Exam only 2 days after it was released. Going into the exam blind, I wasn’t too worried because the previous OCA 8 1Z0-808 exam had been such a breeze. Boy was I surprised! While I passed with a decent margin, I was shocked the level of difficulty of the Programmer I 1Z0-815 exam. It was nothing like the 1Z0-808 exam it inherits from, especially in terms of question difficulty!

This past month, Jeanne and I finished writing our new Java OCP 11 Programmer I Study Guide (now available for preorder), which meant it was time to turn our attention to our upcoming Java OCP 11 Programmer II Study Guide. Rather than go in blind, and especially given all of the new material, I decided to spend some time studying *before* taking the 1Z0-816 exam. Well, it paid off because I passed today with a quite a wide margin. Below are some of my impressions of the exam.

Level of Difficulty

This might sound crazy, and I’m sure I’m biased, but overall I found the 1Z0-816 OCP11 exam less difficult than the OCP 8 1Z0-809 exam it inherits from. Don’t get me wrong, it was a difficult exam, but I felt like there were so many topics and they were so broad, the exam rarely went into especially deep detail on some of them. For example, many of the questions regarding SQL injection had pretty clear answers. In most of the questions, I was able to eliminate completely “ridiculous” answers right away, getting the answer choices down to 2 (or 3 if it was pick 2, or 4 if it was pick 3, etc). In fact, some questions I didn’t even need to read the text to whittle down the answer choices. For example, if an answer choice is an invalid lambda expression, it clearly cannot be a valid answer. With that in mind, most questions boiled down eliminating bad answers, then reading the question text to know which of the two remaining choices was correct.

Better Focused

One of the best changes they made in the new 1Z0-815/1Z0-816 exam series was to move most of the core Java syntactical questions to the first exam. While they made the 1Z0-815 exam harder, it made the 1Z0-816 exam a lot clearer. For example, if a question appears to be about NIO.2 on the 1Z0-816 exam, then it’s about NIO.2! On the older 1Z0-809 exam, I always felt like they mixed common Java topics with advanced ones. For example, a question that appears to be about NIO.2 on the 1Z0-809 exam might actually be about constructor overloading or overriding methods. In other words, the 1Z0-816 exam is better because the questions are derived from the objectives more cleanly, and there aren’t as many trick questions. You still have to know a lot to pass, but at least they aren’t mixing topics as much as they did in previous exams.

Streams, Streams, Streams

While the exam seemed reasonable to me, I’m also very proficient in streams. It is an understatement to say they are all over the exam. If you don’t use them regularly, you’ll need a lot of practice before taking the exam. Remember, they can show up in almost any topic like NIO.2, Concurrency, Collections, etc.

Modules

Modules are on the exam but I found the questions a lot more straight-forward than the module questions I saw on the 1Z0-815 exam. I had a lot of trouble with the module questions on the 1Z0-815 exam, in part because a lot of them didn’t make sense or didn’t appear to have a correct answer. Given how early I took the exam, Jeanne suspects I might have been exposed to beta/experimental/broken questions. That said, I thought the module questions on the 1Z0-816 exam were a lot more fair than they were on the 1Z0-815 exam. You need to know a lot about modules, of course, but the topics the questions were testing were a lot clearer.

Still a Very Broad Exam

While questions within a topic were relatively straight-forward, the amount of topics you had to know for the 1Z0-816 exam dwarfs the 1Z0-809 exam. Annotations, Security, Local Type Inference, Private/Static Interface Methods, and Modules are completely new. You should read the Secure Coding Guideline and Annotations Trail prior to taking the exam. Unfortunately, there’s not one single source of material for modules so you have to study from what you can piece together on the web… that is until our new 1Z0-816 study guide is released!

So You Want to Take the Exam?

Great! If you’re not in a hurry, I would wait for our new study guides to come out. The first book is already on its way to print and the second book will be available early next year. You can use our OCP 8 Study Guide to take exam, but you will have to supplement it with a lot of reading from a dozen different sources. And as I said earlier, if you’re not using streams regularly, you will definitely need a lot of practice. Regardless of which path you take, we wish you the best in studying!