Java Coding Problems
eBook - ePub

Java Coding Problems

Improve your Java Programming skills by solving real-world coding challenges

Anghel Leonard

Share book
  1. 816 pages
  2. English
  3. ePUB (mobile friendly)
  4. Available on iOS & Android
eBook - ePub

Java Coding Problems

Improve your Java Programming skills by solving real-world coding challenges

Anghel Leonard

Book details
Book preview
Table of contents
Citations

About This Book

Develop your coding skills by exploring Java concepts and techniques such as Strings, Objects and Types, Data Structures and Algorithms, Concurrency, and Functional programming

Key Features

  • Solve Java programming challenges and get interview-ready by using the power of modern Java 11
  • Test your Java skills using language features, algorithms, data structures, and design patterns
  • Explore areas such as web development, mobile development, and GUI programming

Book Description

The super-fast evolution of the JDK between versions 8 and 12 has increased the learning curve of modern Java, therefore has increased the time needed for placing developers in the Plateau of Productivity. Its new features and concepts can be adopted to solve a variety of modern-day problems. This book enables you to adopt an objective approach to common problems by explaining the correct practices and decisions with respect to complexity, performance, readability, and more.

Java Coding Problems will help you complete your daily tasks and meet deadlines. You can count on the 300+ applications containing 1, 000+ examples in this book to cover the common and fundamental areas of interest: strings, numbers, arrays, collections, data structures, date and time, immutability, type inference, Optional, Java I/O, Java Reflection, functional programming, concurrency and the HTTP Client API. Put your skills on steroids with problems that have been carefully crafted to highlight and cover the core knowledge that is accessed in daily work. In other words (no matter if your task is easy, medium or complex) having this knowledge under your tool belt is a must, not an option.

By the end of this book, you will have gained a strong understanding of Java concepts and have the confidence to develop and choose the right solutions to your problems.

What you will learn

  • Adopt the latest JDK 11 and JDK 12 features in your applications
  • Solve cutting-edge problems relating to collections and data structures
  • Get to grips with functional-style programming using lambdas
  • Perform asynchronous communication and parallel data processing
  • Solve strings and number problems using the latest Java APIs
  • Become familiar with different aspects of object immutability in Java
  • Implement the correct practices and clean code techniques

Who this book is for

If you are a Java developer who wants to level-up by solving real-world problems, then this book is for you. Working knowledge of Java is required to get the most out of this book.

Frequently asked questions

How do I cancel my subscription?
Simply head over to the account section in settings and click on “Cancel Subscription” - it’s as simple as that. After you cancel, your membership will stay active for the remainder of the time you’ve paid for. Learn more here.
Can/how do I download books?
At the moment all of our mobile-responsive ePub books are available to download via the app. Most of our PDFs are also available to download and we're working on making the final remaining ones downloadable now. Learn more here.
What is the difference between the pricing plans?
Both plans give you full access to the library and all of Perlego’s features. The only differences are the price and subscription period: With the annual plan you’ll save around 30% compared to 12 months on the monthly plan.
What is Perlego?
We are an online textbook subscription service, where you can get access to an entire online library for less than the price of a single book per month. With over 1 million books across 1000+ topics, we’ve got you covered! Learn more here.
Do you support text-to-speech?
Look out for the read-aloud symbol on your next book to see if you can listen to it. The read-aloud tool reads text aloud for you, highlighting the text as it is being read. You can pause it, speed it up and slow it down. Learn more here.
Is Java Coding Problems an online PDF/ePUB?
Yes, you can access Java Coding Problems by Anghel Leonard in PDF and/or ePUB format, as well as other popular books in Computer Science & Programming in Java. We have over one million books available in our catalogue for you to explore.

Information

Year
2019
ISBN
9781789800500
Edition
1

Arrays, Collections, and Data Structures

This chapter includes 30 problems that involve arrays, collections, and several data structures. The aim is to provide solutions to a category of problems encountered in a wide range of applications, including sorting, finding, comparing, ordering, reversing, filling, merging, copying, and replacing. The solutions provided are implemented in Java 8-12 and they can also be used as a basis for solving other related issues. At the end of this chapter, you will have at your disposal a solid breadth of knowledge that will prove useful in solving a variety of problems involving arrays, collections, and data structures.

Problems

Use the following problems to test your programming prowess based on arrays, collections, and data structures. I strongly encourage you to give each problem a try before you turn to the solutions and download the example programs:
  1. Sorting an array: Write several programs that exemplify different sorting algorithms for arrays. Also, write a program for shuffling arrays.
  2. Finding an element in an array: Write several programs that exemplify how to find the given element (primitive and object) in a given array. Find the index and/or simply check whether the value is in the array.
  3. Checking whether two arrays are equal or mismatches: Write a program that checks whether the two given arrays are equals or whether there is a mismatch.
  4. Comparing two arrays lexicographically: Write a program that compares the given arrays lexicographically.
  1. Creating a stream from an array: Write a program that creates a stream from the given array.
  2. Minimum, maximum, and average of an array: Write a program that computes the maximum, minimum, and average of the given array.
  3. Reversing an array: Write a program that reverses the given array.
  4. Filling and setting an array: Write several examples for filling up an array and setting all elements based on a generator function to compute each element.
  5. Next Greater Element (NGE): Write a program that returns the NGE for each element of an array.
  6. Changing array size: Write a program that adds an element to an array by increasing its size by one. In addition, write a program that increases the size of an array with the given length.
  7. Creating unmodifiable/immutable collections: Write several examples that create unmodifiable and immutable collections.
  8. Mapping a default value: Write a program that gets a value from Map or a default value.
  9. Computing whether absent/present in a Map: Write a program that computes the value of an absent key or a new value of a present key.
  10. Removal from a Map: Write a program that removes from a Map by means of the given key.
  11. Replacing entries from a Map: Write a program that replaces the given entries from a Map.
  12. Comparing two maps: Write a program that compares two maps.
  13. Merging two maps: Write a program that merges two given maps.
  14. Copying HashMap: Write a program that performs a shallow and deep copy of HashMap.
  15. Sorting a Map: Write a program that sorts a Map.
  16. Removing all elements of a collection that match a predicate: Write a program that removes all elements of a collection that match the given predicate.
  17. Converting a collection into an array: Write a program that converts a collection into an array.
  18. Filtering a collection by List: Write several solutions for filtering a collection by a List. Reveal the best way of doing this.
  19. Replacing elements of a List: Write a program that replaces each element of a List with the result of applying a given operator to it.
  20. Thread-safe collections, stacks, and queues: Write several programs that exemplify the usage of Java thread-safe collections.
  21. Breadth-first search (BFS): Write a program that implements the BFS algorithm.
  22. Trie: Write a program that implements a Trie data structure.
  23. Tuple: Write a program that implements a Tuple data structure.
  24. Union Find: Write a program that implements the Union Find algorithm.
  25. Fenwick Tree or Binary Indexed Tree: Write a program that implements the Fenwick Tree algorithm.
  26. Bloom filter: Write a program that implements the Bloom filter algorithm.

Solutions

The following sections describe solutions to the preceding problems. Remember that there usually isn't a single correct way to solve a particular problem. Also, remember that the explanations shown here include only the most interesting and important details needed to solve the problems. Download the example solutions to see additional details and to experiment with the programs at https://github.com/PacktPublishing/Java-Coding-Problems.

99. Sorting an array

Sorting an array is a common task encountered in a lot of domains/applications. It is so common that Java provides a built-in solution for sorting arrays of primitives and objects using a comparator. This solution works very well and is the preferable way to go in most of the cases. Let's take a look at the different solutions in the next section.

JDK built-in solutions

The built-in solution is named sort() and it comes in many different flavors in the java.util.Arrays class (15+ flavors).
Behind the sort() method, there is a performant sorting algorithm of the Quicksort type, named Dual-Pivot Quicksort.
Let's assume that we need to sort an array of integers by natural order (primitive int). For this, we can rely on Arrays.sort(int[] a), as in the following example:
int[] integers = new int[]{...};
Arrays.sort(integers);
Sometimes, we need to sort an array of an object. Let's assume that we have a class as Melon:
public class Melon {

private final String type;
private final int weight;

public Melon(String type, int weight) {
this.type = type;
this.weight = weight;
}

// getters omitted for brevity
}
An array of Melon can be sorted by ascending weight via the proper Comparator:
Melon[] melons = new Melon[] { ... };

Arrays.sort(melons, new Comparator<Melon>() {
@Override
public int compare(Melon melon1, Melon melon2) {
return Integer.compare(melon1.getWeight(), melon2.getWeight());
}
});
The same result can be obtained by rewriting the preceding code via a lambda expression:
Arrays.sort(melons, (Melon melon1, Melon melon2) 
-> Integer.compare(melon1.getWeight(), melon2.getWeight()));
Moreover, arrays provide a method for sorting elements in parallel, parallelSort(). The sorting algorithm used behind the scenes is a parallel sort-merge based on ForkJoinPool that breaks up the array into sub-arrays that are themsel...

Table of contents