↓ Skip to main content
Streams

Nth Prime

·2 mins
Table of Contents

Prime number is an age old problem. I am trying to solve it via streams.

class PrimeCalculator {

    public int nth(int nth) {
        if (nth <= 0)
            throw new IllegalArgumentException();

        // Will skip the nth - 1
        // 2 to n-1
        return IntStream.iterate(2, i -> i + 1).filter(PrimeCalculator::isPrime).skip(nth - 1).findFirst().getAsInt();
    }

    public static boolean isPrime(int x) {
        // till half of x
        return IntStream.rangeClosed(2, (int) (x/2) ).dropWhile(i -> x % i != 0).findFirst().isEmpty();
    }
}

Explanation
#

public int nth(int nth) {
        if (nth <= 0)
            throw new IllegalArgumentException();

        // Will skip the nth - 1
        // 2 to n-1
        return IntStream.iterate(2, i -> i + 1).filter(PrimeCalculator::isPrime).skip(nth - 1).findFirst().getAsInt();
    }

The method nth(int) allows you to return the nth prime starting at 2, 3, 5....

  • If the nth is negative or l.t.e 0 return an illegal argument exception.
  • Else, Iterate 2 onwards
  • Filter all the elements that are prime.
  • Skip all n - 1 elements.
  • Find first and return it as int.
static <T> Stream<T> iterate(T seed,
                             UnaryOperator<T> f)
Returns an infinite sequential ordered Stream produced by iterative application of a function f to an initial element seed.
Stream<T> skip(long n)
Skip is a stateful intermediate operation.

Skip() Returns a stream consisting of the remaining elements of this stream after discarding the first n elements of the stream. If this stream contains fewer than n elements then an empty stream will be returned.

from java docs

Optional<T> findFirst()
findFirst is a short-circuiting terminal operation — java docs

An intermediate operation is short-circuiting if, when presented with infinite input, it may produce a finite stream as a result. A terminal operation is short-circuiting if, when presented with infinite input, it may terminate in finite time.

java docs

Helpers
#

Author
Samarthya
Engineer, learner, tinkerer. This is my trophy shelf of everyday work and leisure.

Related

JavaStream: Characters

·1 min
Continuing from the last blog how about checking a pangram using streams. public class PangramChecker { private String allChars = "abcdefghijklmnopqrstuvwxyz"; public boolean isPangram(String input) { if (input.length() <= 0 || input.isBlank()){ return false; } return (allChars.chars().map(x -> (char) x).filter(x -> input.toLowerCase().indexOf(x) >= 0).count() == 26); } } All the for loops have been squeezed into a simple line

Java Streams

·2 mins
Stream is an new abstraction that lets one process data in a declarative way. A stream does not store data and, in that sense, is not a data structure. It also never modifies the underlying data source. The easiest way to learn a new API or a construct is by trying it. So here is an exercise that I tried to learn the Stream API. This is an exercise from exercism.io.

Consumer

The utility package java.util.function has this functional interface Consumer. Each functional interface (Annotated with @FunctionalInterface) conceptually has a single method (abstract) called the functional method to which the lambda expression’s parameter and return types are matched against. Functional interfaces often represent abstract concepts like functions, actions, or predicates.