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

Monday, May 31, 2021

Go (Con)Figure

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

Another post about Lightweight Config, a library I’ve recently built from the ground up, after creating various versions of it in previous projects.

Where previously, I’d tried to be clever and prepare the library for lots of possibilities, I took the opposite approach this time. I created a simple monolithic library to solve the core problem, and then in a later version added some new ideas that the simple idea opened up for me.

The Basic Challenge

In a service that has no specific injection framework, like Spring or DropWizard, and especially in a test, what’s the nicest way to load some configuration into an object.

E.g.

username: user

password: foo

urls:

  - http://foo.com

  - http://bar.com

We’d like to load this into an object:

public class Config {

    private String user;

    private String password;

    private List<String> urls;

    // getters and setters

}

This is easily achieved in one line with ConfigLoader.loadYmlConfigFromResource("config.yml", Config.class)

This assumes config.yml is in the appropriate resources.

Placeholders

What if we wanted to interpolate runtime values from environment variables or system properties? Well, that’s really the point of this framework. It’s intended to externalise the setting of values:

username: ${USERNAME}

password: ${PASSWORD}

urls:

  - http://foo.com

  - http://bar.com

Imports

If we have some common snippets of configuration to share between various configuration objects, then an import syntax would be nice. Even better if we can drive the import by a placeholder:

# config.yml

#import ${PROFILE}-config.yml

And then:

# dev-config.yml

username: username

password: foo

urls:

   - http://www.dev.com

Core Java, Oracle Java Tutorial and Material, Oracle Java Certification, Oracle Java Preparation
And so on. Now we can load the config.yml but set PROFILE to determine which child config is also loaded. We can even put some common properties in the parent and it’ll all mash together into the load operation.

Plugins

What if we’re using a password/secret manager to load certain values dynamically? Let’s say we want to express that a certain value may be loaded from a secret:

username: !secret ${SECRET_ID}.user

password: !secret ${SECRET_ID}.password

We can add our custom tag – secret – to the loader:

Config myConfig = new ConfigLoader()

    .withTag("secret", secretPath -> secretsManager.load(secretPath))

    .loadAs("config.yml", Config.class);

Source: codingcraftsman.wordpress.com