Saturday, October 31, 2015

Java 8 Streams API: Finding and matching

The Streams API provides some useful methods to determine whether elements in a stream match a given condition.

The anyMatch method can be used to check if there exists an element in the stream that matches a given predicate. For example, to find out whether a stream of random numbers has a number greater than 5:

IntStream randomStream = new Random(100, 1, 11);
if (randomStream.anyMatch(i -> i > 5)) {
 System.out.println("The stream has a number greater than 5");

The allMatch method can be used to check if all elements in the stream match a given predicate. For example, to find out whether a stream of random numbers only contains positive numbers:

boolean isPositive = randomStream.allMatch(i -> i > 0);

noneMatch is the opposite of allMatch and can be used to check that no elements in the stream match a given predicate. The previous example could be rewritten using noneMatch as follows:

boolean isPositive = randomStream.noneMatch(i -> i <= 0);

The findAny method returns an arbitrary element of the stream. It returns an Optional because it's possible that no element might be returned by findAny. For example, to find a number greater than 5 in our random number stream:

OptionalInt number = randomStream.filter(i -> i > 5)

findFirst is similar to findAny but returns the first element in the stream. For example, to find the first number greater than 5 in our random number stream:

OptionalInt number = randomStream.filter(i -> i > 5)

The difference between findAny and findFirst arises when using parallel streams. Finding an arbitrary element in a stream is less constraining than finding the first element, when running in parallel mode, so findAny may perform better. So, if you don't care about which element is returned, use findAny.

An interesting thing to note is that the operations described above use short-circuiting i.e. they don't need to process the entire stream to produce a result. As soon as an appropriate element is found, a result is returned.

Sunday, September 06, 2015

Stack Overflow - swag!

After waiting for what has seemed like forever, my Stack Overflow box of swag has finally arrived! The nice people at Stack Overflow sent me this stuff to congratulate me for reaching 100,000 reputation!

The box contained a:

  • t-shirt,
  • mug,
  • moleskin notebook, embossed with the Stack Overflow logo, and
  • stickers of various Stack Exchange sites that I participate in.

Here are a couple of pictures:

Reverse of mug:

Sunday, July 26, 2015

Java 8: Creating infinite streams

There are many ways you can build a Stream in Java 8. One of the most common ways, is to get a stream from a collection using the stream method as shown below:

List<String> list = Arrays.asList("Alice", "Bob");
Stream<String> stream =;

You can also create a stream from values using the static method, Stream.of:

Stream<String> stream = Stream.of("Alice", "Bob");

Arrays can be converted to streams using the static method,

int[] numbers = { 1, 3, 6, 8 };
IntStream stream =;
Creating infinite streams:

The Streams API provides two static methods: Stream.iterate and Stream.generate, which allow you to create an infinite stream. Here's an example:

Stream<Integer> evenNumbers = Stream.iterate(0, n -> n + 2);

The example above produces an infinite stream of even numbers. The iterate method takes a starting value and a lambda that is used to generate a new value from the previous one. In this case, the lambda returns the previous value added with 2. The stream is infinite because values are computed on demand and can be computed forever. (Note that you can use the limit method to explicitly limit the size of the stream.)

Similarly, Stream.generate also lets you produce an infinite stream, but the difference is that it takes a lamba of type Supplier<T> to provide new values, rather than a lambda that applies successively to the previous value. Here's an example:

Stream<Integer> randomNumbers = Stream.generate(Math::random);

Sunday, June 28, 2015

Java 8: Composing Comparators

In my last post, I showed how you can sort a list of Person objects by age, using the following statement:


What if you want to sort the objects in order of decreasing age instead? There's no need to create a new instance of Comparator, because the Comparator interface has a handy default method reversed that reverses its ordering:


Now, what if you want to sort people by name if they have the same age. The thenComparing method allows you to do just that, as shown below:


Saturday, June 27, 2015

Java 8: Sorting a List using Lambdas and Method References

This post shows how you can use Java 8 lambda expressions and method references to sort a list of Person objects by age. In Java 8, the List interface has a sort method, which expects a Comparator to compare two objects.

Traditionally, you would either sort a list by creating a specific class that implements the Comparator interface, like this:

public class AgeComparator implements Comparator<Person> {
  public int compare(Person p1, Person p2) {
    return, p2.getAge());

list.sort(new AgeComparator());

or, you would use an anonymous class, like this:

list.sort(new Comparator<Person>() {
  public int compare(Person p1, Person p2) {
    return, p2.getAge());

As you can see, this is quite verbose!

Java 8 introduces lambda expressions, which allow you to pass code more concisely. Since Comparator is a functional interface, you can use a lambda expression to sort the list:

list.sort((p1, p2) ->, p2.getAge()));

You may have noticed that the Comparator class has a static method called comparingInt that takes a ToIntFunction and returns a Comparator object. So, we can rewrite the code above to:

import static java.util.Comparator.comparingInt;
list.sort(comparingInt(p -> p.getAge()));

Finally, we can improve our code even further by using a method reference, which is just "syntactic sugar" for a lambda expression:


The final solution is not only shorter but is also easier to read :)