Monday, June 14, 2021

Java Spark RDD reduce() Examples – sum, min and max operations

Java Spark RDD Reduce, Core Java, Oracle Java Preparation, Oracle Java Certification, Oracle Java Career

A quick guide to explore the Spark RDD reduce() method in java programming to find sum, min and max values from the data set.

1. Overview

In this tutorial, we will learn how to use the Spark RDD reduce() method using java programming language. Most of the developers use the same method reduce() in pyspark but in this article, we will understand

how to get the sum, min and max operations with Java RDD.

2. Java Spark RDD – reduce() method

First let understand the syntax of java reduce() spark method.

public T reduce(scala.Function2<T,T,T> f)

This method takes the Function2 functional interface which is the concept of Java 8. But the Function2 is implemented in Scala language.

Function2 takes two arguments as input and returns one value. Here, always input and output type should be same.

3. Java Spark RDD reduce() Example to find sum


In the below examples, we first created the SparkConf and JavaSparkContext with local mode for the testing purpose.

We’ve provided the step by step meaning in the program.

We must have to pass the lambda expression to the reduce() method.

You might be surprised with the logic behind the reduce() method. Below is the explanation of its internals. As a developer, you should know the basic knowledge on hood what is going on.

Java Spark RDD Reduce, Core Java, Oracle Java Preparation, Oracle Java Certification, Oracle Java Career
On the RDD, reduce() method is called with the logic of value1 + value2. That means this formula will be applied to all the values in each partition untill partition will have only one value.

If there are more than one partitions then all the outputs of partitions are moved to another data node. Then next, again the same logic value1 + value2 is applied to get the final result.

if only one partition is for the input file or dataset then it will return the final output of the single partion.

package com.oraclejavacertified.rdd.reduce;
 
import java.util.Arrays;
import java.util.List;
 
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
 
public class RDDReduceExample {
 
    public static void main(String[] args) {
         
        // to remove the unwanted loggers from output.
        Logger.getLogger("org.apache").setLevel(Level.WARN);
 
        // Getting the numbers list.
        List<Integer> numbersList = getSampleData();
         
        // Creating the SparkConf object
        SparkConf sparkConf = new SparkConf().setAppName("Java RDD_Reduce Example").setMaster("local");
 
        // Creating JavaSprakContext object
        JavaSparkContext sc = new JavaSparkContext(sparkConf);
         
        // Converting List into JavaRDD.
        JavaRDD<Integer> integersRDD =  sc.parallelize(numbersList);
         
        // Getting the sum of all numbers using reduce() method
        Integer sumResult = integersRDD.reduce( (value1, value2) -> value1 + value2);
 
        // printing the sum
         
        System.out.println("Sum of RDD numbers using reduce() : "+sumResult);
         
        // closing Spark Context
        sc.close();
         
    }
 
    /**
     * returns a list of integer numbers
     * 
     * @return
     */
    private static List<Integer> getSampleData() {
 
        return Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
 
    }
 
}

Output:

Sum of RDD numbers using reduce() : 45

4. Java Spark RDD reduce() min and max Examples


Next, let us find the min and max values from the RDD.

package com.oraclejavacertified.rdd.reduce;
 
import java.util.Arrays;
import java.util.List;
 
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
 
public class RDDReduceExample {
 
    public static void main(String[] args) {
         
        // to remove the unwanted loggers from output.
        Logger.getLogger("org.apache").setLevel(Level.WARN);
 
        // Getting the numbers list.
        List<Integer> numbersList = getSampleData();
         
        // Creating the SparkConf object
        SparkConf sparkConf = new SparkConf().setAppName("Java RDD_Reduce Example").setMaster("local");
 
        // Creating JavaSprakContext object
        JavaSparkContext sc = new JavaSparkContext(sparkConf);
         
        // Converting List into JavaRDD.
        JavaRDD<Integer> integersRDD =  sc.parallelize(numbersList);
         
        // Finding Min and Max values using reduce() method
         
        Integer minResult = integersRDD.reduce( (value1, value2) -> Math.min(value1, value2));
         
        System.out.println("Min of RDD numbers using reduce() : "+minResult);
         
        Integer maxResult = integersRDD.reduce( (value1, value2) -> Math.max(value1, value2));
         
        System.out.println("Max of RDD numbers using reduce() : "+maxResult);
         
        // closing Spark Context
        sc.close();
         
    }
 
    /**
     * returns a list of integer numbers
     * 
     * @return
     */
    private static List<Integer> getSampleData() {
 
        return Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
 
    }
 
}

Output:

Min of RDD numbers using reduce() : 1
Max of RDD numbers using reduce() : 9

Source: javacodegeeks.com

Friday, June 11, 2021

Java - Data Structures

Java - Data Structures, Core Java, Oracle Java Tutorial and Material, Oracle Java Preparation

The data structures provided by the Java utility package are very powerful and perform a wide range of functions. These data structures consist of the following interface and classes −

◉ Enumeration

◉ BitSet

◉ Vector

◉ Stack

◉ Dictionary

◉ Hashtable

◉ Properties

All these classes are now legacy and Java-2 has introduced a new framework called Collections Framework, which is discussed in the next chapter. −

The Enumeration

The Enumeration interface isn't itself a data structure, but it is very important within the context of other data structures. The Enumeration interface defines a means to retrieve successive elements from a data structure.

For example, Enumeration defines a method called nextElement that is used to get the next element in a data structure that contains multiple elements.

To have more detail about this interface, check The Enumeration.

The BitSet

The BitSet class implements a group of bits or flags that can be set and cleared individually.

This class is very useful in cases where you need to keep up with a set of Boolean values; you just assign a bit to each value and set or clear it as appropriate.

For more details about this class, check The BitSet.

The Vector

The Vector class is similar to a traditional Java array, except that it can grow as necessary to accommodate new elements.

Like an array, elements of a Vector object can be accessed via an index into the vector.

The nice thing about using the Vector class is that you don't have to worry about setting it to a specific size upon creation; it shrinks and grows automatically when necessary.

For more details about this class, check The Vector.

The Stack

The Stack class implements a last-in-first-out (LIFO) stack of elements.

You can think of a stack literally as a vertical stack of objects; when you add a new element, it gets stacked on top of the others.

When you pull an element off the stack, it comes off the top. In other words, the last element you added to the stack is the first one to come back off.

For more details about this class, check The Stack.

The Dictionary

The Dictionary class is an abstract class that defines a data structure for mapping keys to values.

This is useful in cases where you want to be able to access data via a particular key rather than an integer index.

Since the Dictionary class is abstract, it provides only the framework for a key-mapped data structure rather than a specific implementation.

For more details about this class, check The Dictionary.

The Hashtable

Java - Data Structures, Core Java, Oracle Java Tutorial and Material, Oracle Java Preparation
The Hashtable class provides a means of organizing data based on some user-defined key structure.

For example, in an address list hash table you could store and sort data based on a key such as ZIP code rather than on a person's name.

The specific meaning of keys with regard to hash tables is totally dependent on the usage of the hash table and the data it contains.

For more detail about this class, check The Hashtable.

The Properties

Properties is a subclass of Hashtable. It is used to maintain lists of values in which the key is a String and the value is also a String.

The Properties class is used by many other Java classes. For example, it is the type of object returned by System.getProperties( ) when obtaining environmental values.

For more detail about this class, check The Properties.

Source: tutorialspoint.com

Wednesday, June 9, 2021

The Subs Bench

Core Java Tutorial and Material, Oracle Java Career, Oracle Java Preparation, Oracle Java Exam Prep

How do I subclass a list element declared in my interface?

In a current project, we’re looking at our strong types having both interfaces and concrete implementations. There’s a reason for this that’s NOT about making things mockable.

Read More: 1Z0-816: Oracle Java SE 11 Programmer II

What’s nice and obvious is that this is possible:

public interface Bar {

}

public interface Foo {

    Bar getBar();

}

public class BarImpl implements Bar {

}

public class FooImpl implements Foo {

    public BarImpl getBar() { ... }

}

Despite the fact that the FooImpl subclass returns a subclass of the interface’s declared getter everything compiles happily, because a subclass can be substituted for a base class and still meet the Liskov substitution principle.

However, there’s a problem if you try to do this:

public interface Foo {

   List<Bar> getBars();

}

public class FooImpl implements Foo {

   // compiler error...

   public List<BarImpl> getBars() { ... }

}

In the Java generic type system, List<BarImpl> is not a subclass of List<Bar>. The folks who designed this stuff are pretty clever, and there’s probably a very good technical reason why this is the case.

The question is – can it be solved?

public interface Foo<T extends Bar> {

    // we know this is "at least" a Bar

    List<T> getBars();

}

public class FooImpl implements Foo<BarImpl> {

    // compiles great

    public List<BarImpl> getBars() { ... }

}

For lots of List or Optional of things, this might seem a bit cumbersome, but it is how it’s done… apparently.

Source: javacodegeeks.com

Monday, June 7, 2021

Stream.reduce() in Java with examples

Core Java, Oracle Java Tutorial and Material, Oracle Java Preparation, Oracle Java Certification, Java Exam Prep

Many times, we need to perform operations where a stream reduces to single resultant value, for example, maximum, minimum, sum, product, etc. Reducing is the repeated process of combining all elements.

More Info: 1Z0-900: Java EE 7 Application Developer

reduce operation applies a binary operator to each element in the stream where the first argument to the operator is the return value of the previous application and second argument is the current stream element.

Syntax :

T reduce(T identity, BinaryOperator<T> accumulator);

Where, identity is initial value 

of type T and accumulator is a 

function for combining two values.

sum(), min(), max(), count() etc. are some examples of reduce operations. reduce() explicitly asks you to specify how to reduce the data that made it through the stream.

Let us see some examples to understand the reduce() function in a better way :

Example 1 :

// Implementation of reduce method

// to get the longest String

import java.util.*;

class GFG {

// Driver code

public static void main(String[] args)

{

// creating a list of Strings

List<String> words = Arrays.asList("GFG", "LPI", "for",

"LPIQuiz", "LPIforLPI");

// The lambda expression passed to

// reduce() method takes two Strings

// and returns the longer String.

// The result of the reduce() method is

// an Optional because the list on which

// reduce() is called may be empty.

Optional<String> longestString = words.stream()

.reduce((word1, word2)

-> word1.length() > word2.length()

? word1 : word2);


// Displaying the longest String

longestString.ifPresent(System.out::println);

}

}

Output :

LPIforLPI

Example 2 :


// Implementation of reduce method
// to get the combined String
import java.util.*;

class GFG {

// Driver code
public static void main(String[] args)
{

// String array
String[] array = { "LPI", "for", "LPI" };

// The result of the reduce() method is
// an Optional because the list on which
// reduce() is called may be empty.
Optional<String> String_combine = Arrays.stream(array)
.reduce((str1, str2)
-> str1 + "-" + str2);

// Displaying the combined String
if (String_combine.isPresent()) {
System.out.println(String_combine.get());
}
}
}

Output :

LPI-for-LPI

Example 3 :


// Implementation of reduce method
// to get the sum of all elements
import java.util.*;

class GFG {

// Driver code
public static void main(String[] args)
{

// Creating list of integers
List<Integer> array = Arrays.asList(-2, 0, 4, 6, 8);

// Finding sum of all elements
int sum = array.stream().reduce(0,
(element1, element2) -> element1 + element2);

// Displaying sum of all elements
System.out.println("The sum of all elements is " + sum);
}
}

Output :

The sum of all elements is 16

Example 4 :


Core Java, Oracle Java Tutorial and Material, Oracle Java Preparation, Oracle Java Certification, Java Exam Prep
// Implementation of reduce method
// to get the product of all numbers
// in given range.
import java.util.*;
import java.util.stream.IntStream;

class GFG {

// Driver code
public static void main(String[] args)
{

// To get the product of all elements
// in given range excluding the
// rightmost element
int product = IntStream.range(2, 8)
.reduce((num1, num2) -> num1 * num2)
.orElse(-1);

// Displaying the product
System.out.println("The product is : " + product);
}
}

Output :

The product is : 5040

Friday, June 4, 2021

The Secret Weapon of Top Performing Companies? It’s All in Who You Ask.

Core Java, Oracle Java Tutorial and Material, Oracle Java Preparation, Oracle Java Career 

William Blake once said, “What is now proved was once only imagined.” Java has been the platform of choice for millions of developers over the past 25 years to take what’s imagined and make it real.

Read More: 1Z0-900: Java EE 7 Application Developer

In his new book, “Ask Your Developer: How to harness the power of software development to win the 21st century”, author Jeff Lawson shares an analogy about the ongoing pressure of businesses to stay ahead of their competitors with innovation. He writes, “In Ford v. Ferrari, the film about Ford’s quest to win the 24 Hours of Le Mans race, there’s a great scene where Ford has finally managed to defeat Ferrari at Le Mans with an astonishing racer called the GT40. “She’s a hell of a machine,” Ken Miles, the driver, tells Carroll Shelby, the designer. But instead of basking in the glory, Miles and Shelby immediately start talking about ways to make the GT40 faster…Everyone feels the pressure to go faster, do more work in less time with fewer people, keep from falling behind.”


The Secret Weapon of Top Performing Companies? It’s All in Who You Ask.

“Business transformation” and “digital transformation” seem to have become today’s lingua franca and the mechanisms by which companies look to stay ahead of their competitors and to more effectively meet the needs of their customers.

As Jeff and I will discuss during our upcoming fireside chat webinar April 8 (Americas) and 13 (EMEA and APAC), “The Secret Weapon of Top Performing Companies? It’s All in Who You Ask” successful business transformation requires drawing from the strength of all your assets, particularly people and technology. From the “people” perspective, top performing companies engage the developer in their business transformation strategy planning. While this seems logical, it’s not entirely common. More often, companies look to developers to implement requirements, not necessarily participate in the conversation to scope them out. Developers are the very people with the most knowledge of how application investments can be best leveraged and modernized to meet business goals. These successful companies don’t just hand the car design over to the engineers without knowing what is possible. The engineer is at the table the whole time.

From a technology perspective, applications are the work horse that will drive the car to victory. However, challenges of maintaining applications on supported and unsupported software versions, which can open you up to security and stability risk, and managing a complex application estate, can take your most creative development resources from “full throttle” to “neutral”. 

As we increasingly shift towards a digital economy, the pace of innovation and transformation continues to accelerate, driving companies to look at new ways of winning. Companies are shifting how they work, how they deliver services and how they adjust to customer preferences. Keeping your application portfolio stable and secure while having the agility to modernize with microservices and cloud-native development is crucial in the ongoing race for market share and customer mindshare. Today’s advantage becomes tomorrow’s commodity and you must have the agility to move to what’s next to stay in the race.

Oracle, with its Java SE Subscription service, which now includes the GraalVM Enterprise entitlement at no additional cost, supports its customers thru their application evolution journey. Java SE Subscription protects the investment across the entire Java application base, and GraalVM Enterprise delivers higher performance while consuming less resources. With this powerful combination, Oracle keeps our customers driving forward at the pace of their business.

Source: oracle.com

Wednesday, June 2, 2021

Apache Arrow on the JVM: Streaming Reads

JVM Exam Prep, JVM Certification, JVM Tutorial and Material, JVM Career, Oracle Java Preparation, Oracle Java Exam Prep

Previously we wrote Arrow Data to a Stream. Now we shall read those data from a stream.

Just like on the previous blog the we shall implement the Closeable interface. This is needed to close the RootAllocator and free-up memory.

We shall pass a ReadableByteChannel and thus get the stream into read objects. 

package com.gkatzioura.arrow;

import java.io.Closeable;

import java.io.IOException;

import java.nio.channels.ReadableByteChannel;

import java.util.ArrayList;

import java.util.List;

import org.apache.arrow.memory.RootAllocator;

import org.apache.arrow.vector.IntVector;

import org.apache.arrow.vector.VarCharVector;

import org.apache.arrow.vector.ipc.ArrowStreamReader;

public class DefaultEntriesReader implements Closeable {

    private final RootAllocator rootAllocator;

    public DefaultEntriesReader() {

        rootAllocator = new RootAllocator(Integer.MAX_VALUE);

    }

    public List<DefaultArrowEntry> readBytes(ReadableByteChannel readableByteChannel) throws IOException {

        List<DefaultArrowEntry> defaultArrowEntries = new ArrayList<>();

        try(ArrowStreamReader arrowStreamReader = new ArrowStreamReader(readableByteChannel, rootAllocator)) {

            var root = arrowStreamReader.getVectorSchemaRoot();

            var childVector1 = (VarCharVector)root.getVector(0);

            var childVector2 = (IntVector)root.getVector(1);

            while (arrowStreamReader.loadNextBatch()) {

                int batchSize = root.getRowCount();

                for (int i = 0; i < batchSize; i++) {

                    var strData = new String(childVector1.get(i));

                    var intData = childVector2.get(i);

                    DefaultArrowEntry defaultArrowEntry = DefaultArrowEntry.builder().col1(strData).col2(intData).build();

                    defaultArrowEntries.add(defaultArrowEntry);

                }

            }

            return defaultArrowEntries;

        }

    }

    @Override

    public void close() throws IOException {

        rootAllocator.close();

    }

}

JVM Exam Prep, JVM Certification, JVM Tutorial and Material, JVM Career, Oracle Java Preparation, Oracle Java Exam Prep
Let’s wrap it up with a write and a Read

package com.gkatzioura.arrow;

import java.io.ByteArrayInputStream;

import java.io.ByteArrayOutputStream;

import java.io.IOException;

import java.nio.channels.Channels;

import java.util.stream.Collectors;

import java.util.stream.IntStream;

public class ArrowMain {

    public static void main(String[] args) throws IOException {

        var originalEntries = IntStream.rangeClosed(0, 11)

                             .boxed()

                             .map(i -> new DefaultArrowEntry("data-"+i, i)).collect(Collectors.toList());

        var outputStream = new ByteArrayOutputStream();

        try(var arrowWriter = new DefaultEntriesWriter()) {

            arrowWriter.write(originalEntries, 10, Channels.newChannel(outputStream));

        }

        byte[] introBytes = outputStream.toByteArray();

        var inputStream = new ByteArrayInputStream(introBytes);

        try(var arrowReader = new DefaultEntriesReader()) {

            var entries =arrowReader.readBytes(Channels.newChannel(inputStream));

            for (DefaultArrowEntry entry : entries) {

                System.out.println("Read "+entry.getCol1()+" "+entry.getCol2());

            }

        }

    }

}

Source: javacodegeeks.com