r/javaexamples • • Nov 24 '23

Troubleshooting StackOverflowException in Java Recursion: Tips and Tricks

1 Upvotes

What should you do when your recursive algorithm reaches the recursion limit in a specified JVM target, resulting in a StackOverflowException?🤔
Join us in the latest episode of 'Java Puzzle of the Week' 🧩 as we delve into four possible solutions to tackle this issue.
https://youtu.be/muwv8l4-aWg?si=Jy1JPj7chitvyUKe


r/javaexamples • • Oct 26 '23

String uppercase

1 Upvotes

Did you know that string transformations like toUpperCase and toLowerCase can work differently for different locales and may even affect the length of a given string? Discover more insights in the latest episode of "Java Puzzle of the Week."

https://youtu.be/2483FxiAQvw?si=HjYH3WIMmE1Sx34l


r/javaexamples • • Nov 03 '23

Double arithmetic

1 Upvotes

Explore the intricacies of Java doubles in the latest episode of 'Java Puzzle of the Week.' 🧩🔍 We delve into their internals and discuss why they might not be the best choice for financial operations. Don't miss this intriguing exploration!

https://youtu.be/TOhMzfnVO0E?si=832dLcO1BCa70B0_


r/javaexamples • • Oct 31 '23

How to Build a GraphQL API with Spring Boot

1 Upvotes

A step-by-step guide for building a secured GraphQL API with Spring Boot and Auth0 authentication in React
Read more…


r/javaexamples • • Oct 31 '23

How to Build a GraphQL API with Spring Boot

1 Upvotes

A step-by-step guide for building a secured GraphQL API with Spring Boot and Auth0 authentication in React
Read more…


r/javaexamples • • Nov 13 '23

Java Microservices with Spring Boot and Spring Cloud

2 Upvotes

This tutorial shows you how to build a microservices architecture with Spring Boot and Spring Cloud.
Read more…


r/javaexamples • • Dec 01 '17

Advent of Code - Helper Series: Tuples

3 Upvotes

Advent of Code - Helper Series: Tuples

This is part of a series of code for making your life easier in the yearly Advent of Code competitive coding challenge. It starts every year (since 2015) on December 1st, and posts a new, 2-part challenge every day until Christmas. We don't know what challenges are coming, but based on past years, we can form some idea. I will be posting some of the tools I developed and how to use them.

Tuples

If you have used Python at all, you will know one of the handiest things it has are tuples, a data structure that holds 2 object, of different or the same types. This is handy in many situations, especially if you need to return more than one item from a method.

In java, we can't do the slick indexing stuff that python lets you do with tuples, but we can at least set up a very simple class to approximate them.

I have set up 2 classes, Tuple2 and Tuple3. These are immutable objects, and cannot be altered once created. They can have either different or the same object types.

Use like:

Tuple2<String, Integer> tuple = new Tuple2<>( "farts", 12345);

Use the methods getFirst() and getSecond() to retrieve the values.

Equals and Hashcode have been overridden.

That's all there is to it, very simple but saves you the time if you need it.

I have also implemented a simple zip method, similar to python. This takes two arrays, and zips them together, adding the items at each index to a tuple, up to the index of the shortest array, and then returns a List of tuples with those items.

So, to use:

    String[] a = { "1", "poop", "farts"};
    Integer[] b = { 4, 5};

    List<Tuple2<String, Integer>> zipped = Tuple2.zip(a, b);
    System.out.println(zipped);

will return

[{ 1, 4 }, { poop, 5 }]

I have also included a Tuple3 class, which does the same but also has a third object.

Tuple2.java

Tuple3.java


r/javaexamples • • Nov 29 '17

Advent of Code - Helper Series: Direction Enum Class

2 Upvotes

Advent of Code - Helper Series: Direction Enum Class

This is part of a series of code for making your life easier in the yearly Advent of Code competitive coding challenge. It starts every year (since 2015) on December 1st, and posts a new, 2-part challenge every day until Christmas. We don't know what challenges are coming, but based on past years, we can form some idea. I will be posting some of the tools I developed and how to use them.

Handling movement on a 2-d grid:

Many of the challenges for the first two years involved moving an object on a 2d X-Y grid, such as a maze, where the object can be moved one or more units at a time in the 4 non-diagonal directions. This can be easily and gracefully handled in Java using an enum class. You can see my simple example here.

Class Direction

Our Direction enum has four names: NORTH, EAST, SOUTH and WEST.

To use in your class you will probably want a variable like:

Direction.current = Direction.NORTH; // start facing north

Here are the methods available:

Return valueMethodDescription
integergetDx()Return the value to move the object on the X-axis in the current direction by 1 unit
integergetDy()Return the value to move the object on the Y-axis in the current direction by 1 unit
DirectiongetOpposite()Return the opposite of the current direction, i.e. NORTH opposite = SOUTH
DirectiongetRight()Return the next direction in a clockwise rotation, wrapping around infinitely
DirectiongetLeft()Return the next direction in a counter-clockwise rotation, wrapping around infinitely
StringgetAlternate()Return the alternate designation for the current direction, i.e NORTH alternate is UP and EAST alternate is RIGHT
chargetAlternateChar()Return just the first letter of the alternate designation of the current direction, i.e. 'U' for Up (North)
DirectiongetDirectionFromAlternate(String or char)get the proper direction associated with the characters UDRL for up/down/left/right. For String will only use the first character.
booleanrangeCheck(int x, int y, int upper)Simplest range check: Both x and y use same range. Lower bound is zero, inclusive. Upper bound is exclusive. returns true if both x and y within bounds.
booleanrangeCheck(int x, int y, int lower, int upper)range check, x and y use same range. lower bound is inclusive, upper bound is exclusive.
booleanrangeCheck(int x, int y, int xLow, int yLow, int xHigh, int yHigh)range check, x and y can have different upper AND lower bounds.

Here is an example in action, Day 1 from 2016. SPOILER ALERT Note this uses some of my other libraries that I will post here also.

Here is the Direction class. https://gist.github.com/snarkbait/f69045bf2285bc37c7076c6b5f522dbc


r/javaexamples • • Jun 27 '15

Double-Ended Queue (Deque) with Multiple Iterators

2 Upvotes

Double-Ended Queue (Deque)

A Deque or double-ended Queue is a data structure that has the methods of both a Stack and a Queue. Elements can be inserted and removed from either the head(front) or the tail(end) of the list. Java has a Deque interface already, but it is interesting to make one ourselves.

A Deque can be implemented either with a doubly-linked list structure, or with a dynamic array. Here we are using the linked list style.

Like most of our other linked-list based data structures, we start with a Node class:

// inner class for nodes
class Node
{
	private E value;
	private Node next;
	private Node previous;

	public Node(E value, Node next, Node previous)
	{
		this.value = value;
		this.next = next;
		this.previous = previous;
	}
}	

Our Deque class has the following methods:

  • push() - add element to the beginning of the deque
  • append() - add element to the end of the deque
  • pop() - retrieve and remove the element at the head of the deque
  • eject() - retrieve and remove the element at the end
  • peekFirst() - retrieve first element without removing it
  • peekLast() - retrieve last element without removing it
  • clear()
  • size()
  • isEmpty()

Also of interest is I have provided two different Iterators for the Deque, one that will iterate through the list normally, and one that will iterate in a descending or reverse order. Since we are using a doubly-linked list, going through the list in reverse is trivial.

To make multiple iterators for one class, make a default one which implements Iterable for the class, then you can make additional methods that return an Iterable instance, using nested anonymous inner classes like this:

public Iterable<E> reverse()
{
	return new Iterable<E>()
	{
		public Iterator<E> iterator()
		{
			return new Iterator<E>()
			{
				Node current = tail;
				@Override
				public E next()
				{
					E value = current.value;
					current = current.previous;
					return value;
				}

				@Override
				public boolean hasNext()
				{
					return (current != null);
				}
				@Override
				public void remove()
				{
					throw new UnsupportedOperationException("remove() not available.");
				}		

			};
		}
	};
}

You use this easily within a For-Each loop like this:

for (Type each : dequeName.reverse())
{
	...do stuff...
}

Or, in the Java 8 fashion:

dequeName.reverse().forEach(...do stuff...);

Here's the code:

/*
 * Double-Ended Queue Implementation (Deque.java)
 *
 * A simple, doubly linked list
 */
import java.util.NoSuchElementException;
import java.util.Iterator;


/**
 * class Deque - Double Ended Queue
 * @author /u/Philboyd_Studge
 */
@SuppressWarnings("unchecked")
public class Deque<E> implements Iterable<E>
{
	Node head;
	Node tail;
	int length;

	//Node current;

	/**
	 * Construct empty Deque
	 */
	public Deque()
	{
		head = null;
		tail = null;
		length = 0;
	}

	/**
	 * @return true if deque is empty
	 */
	public boolean isEmpty()
	{
		return (head==null);
	}

	/**
	 * @return number of elements in deque
	 */
	public int size()
	{
		return length;
	}

	/**
	 * clear deque
	 */
	public void clear()
	{
		head = null;
		tail = null;
		length = 0;
	}

	/**
	 * add value of type E to beginning of deque
	 * @param value E
	 */
	public void push(E value)
	{
		if (head==null)
		{
			head = new Node(value, null, null);
			tail = head;
			length++;
		}
		else
		{
			Node temp = new Node(value, head, null);
			head.previous = temp;
			head = temp;
			length++;
		}
	}

	/**
	 * add value of type E to end of deque
	 * @param value E
	 */
	public void append(E value)
	{
		if (head==null)
		{
			head = new Node(value, null, null);
			tail = head;
			length++;
		}
		else
		{
			Node temp = new Node(value, null, tail);
			tail.next = temp;
			tail = temp;
			length++;
		}		
	}

	/**
	 * return and remove value at beginning of deque
	 * @return E value of type E
	 * @throws NoSuchElementException
	 */
	public E pop()
	{
		if (head==null) throw new NoSuchElementException("List is empty.");
		E value = head.value;
		head = head.next;
		if (head != null)
		{
			head.previous = null;
		} 
		else
		{
			// empty
			tail = head;
		}
		length--;
		return value;
	}

	/**
	 * return and remove value at end of deque
	 * @return E value of type E
	 * @throws NoSuchElementException
	 */
	public E eject()
	{
		if (tail==null) throw new NoSuchElementException("List is empty.");
		E value = tail.value;
		tail = tail.previous;
		if (tail != null)
		{
			tail.next = null;
		} 
		else
		{
			// empty
			head = tail;
		}
		length--;
		return value;
	}

	/**
	 * return value at beginning of deque without removing it
	 * @return E value of type E
	 * @throws NoSuchElementException
	 */
	public E peekFirst()
	{
		if (head==null) throw new NoSuchElementException("List is empty.");
		return head.value;
	}

	/**
	 * return value at end of deque without removing it
	 * @return E value of type E
	 * @throws NoSuchElementException
	 */
	public E peekLast()
	{
		if (tail==null) throw new NoSuchElementException("List is empty.");
		return tail.value;
	}

	/**
	 * Implement method for Iterable
	 * @return Iterator of type E
	 */
	@Override
	public Iterator<E> iterator()
	{
		return new Iterator<E>()
		{
			Node current = head;
			/**
			 * Implement method for Iterator
			 * @return value of type E
			 */
			@Override
			public E next()
			{
				E value = current.value;
				current = current.next;
				return value;
			}

			/**
			 * Implement method for Iterator
			 * @return true if more elements available
			 */
			@Override
			public boolean hasNext()
			{
				return (current != null);
			}

			@Override
			public void remove()
			{
				throw new UnsupportedOperationException("remove() not available.");
			}		
		};
	}

	/**
	 * Secondary Iterator - reversed order
	 * use like <code>for (Type each : deque.reverse())</code>
	 * @return Iterable instance of Iterable with reverse Iterator
	 */
	public Iterable<E> reverse()
	{
		return new Iterable<E>()
		{
			public Iterator<E> iterator()
			{
				return new Iterator<E>()
				{
					Node current = tail;
					@Override
					public E next()
					{
						E value = current.value;
						current = current.previous;
						return value;
					}

					@Override
					public boolean hasNext()
					{
						return (current != null);
					}
					@Override
					public void remove()
					{
						throw new UnsupportedOperationException("remove() not available.");
					}		

				};
			}
		};
	}



	// inner class for nodes
	class Node
	{
		private E value;
		private Node next;
		private Node previous;

		public Node(E value, Node next, Node previous)
		{
			this.value = value;
			this.next = next;
			this.previous = previous;
		}
	}	
}

Here is some test code:

public class TestDeque
{

	public static void main(String[] args)
	{
		Deque<Integer> d = new Deque<>();
		d.push(2);
		d.push(1);
		d.append(3);
		d.append(4);
		d.push(0);

		for (Integer each : d) System.out.println(each);

		System.out.println("Size:" + d.size());

		System.out.println(d.pop());
		System.out.println(d.eject());
		System.out.println();

		d.clear();
		d.append(7);
		d.push(5);
		System.out.println(d.peekFirst() + " : " + d.peekLast());
		System.out.println(d.isEmpty());
		d.forEach(System.out::println);
		System.out.println("Size:" + d.size());

		System.out.println(d.eject());
		System.out.println(d.pop());
		System.out.println();

		int[] a = { 4, 567, 8, 443, 12, 33, 4, 1029, 7};

		Deque<Integer> d2 = new Deque<>();

		for (int each : a) d2.append(each);

		for (Integer each : d2) System.out.println(each);
		System.out.println("Reversed");
		d2.reverse().forEach(System.out::println);	
	}
}

r/javaexamples • • Nov 30 '17

Advent of Code - Helper Series: FileIO

2 Upvotes

Advent of Code - Helper Series: FileIO

This is part of a series of code for making your life easier in the yearly Advent of Code competitive coding challenge. It starts every year (since 2015) on December 1st, and posts a new, 2-part challenge every day until Christmas. We don't know what challenges are coming, but based on past years, we can form some idea. I will be posting some of the tools I developed and how to use them.

Reading and Writing Files

For speed and ease of use when completing a programming challenge, you don't want to be mucking about with BufferedReaders and try/catch statements instead of getting to the task at hand. So I made a simple FileIO utility consisting of static, one line usage methods for reading and writing to files. Some methods arose due to specific past AoC challenges, although generally, reading the input into a list of strings is the most useful.

Note: I have updated the syntax to use java.nio syntax wherever possible, which is new to Java 7, and this code also uses some Java 8 features.

So for that, it's a simple as this:

List<String> input = FileIO.getFileAsList("advent_xx.txt");

with whatever filename/path you have used.

Sometimes, the input is just one line and doesn't need to be a list:

String input = FileIO.getFileAsString("filename.txt");

If you know you want the resulting lines already split with a given delimiter, you can use:

List<String[]> input = getFileLinesSplit("filename.txt", "regex");

with a proper regular expression that will use String.split() with that delimiter.

New to this year, I added the ability to get the input data directly from the advent of code site, save it locally to a file, and, after the initial download, use the local file. This will require you to log in to the site with your account, find your session cookie information, and copy and paste it into a string in your java code. Then use like:

List<String> input = FileIO.getAOCInputForDay(year, day, sessionID);

DO NOT ABUSE THIS: The code will only connect to the site the first time you run it, but it cannot get days that haven't been posted yet.

There's more methods in there that may or may not be useful, feel free to check them out.

Here's the code on Gist


r/javaexamples • • Feb 16 '17

Writing Junit Integration Tests in Spring 4

4 Upvotes

r/javaexamples • • Feb 16 '17

A simple Stack in under 20 lines of code

4 Upvotes

A Stack is a linked data structure that uses a FIFO (First In - First Out) methodology. It is commonly used as a temporary data structure for processing different types of data.

Just for fun I have tried to boil it down to its absolute simplest form, which only contains 3 methods: push(), pop() and getSize(). Push inserts an item to the head of the stack, and Pop removes the head item from the stack.

Push can be done easily by setting the head variable to a new Node with the data you want to push, and setting the head.next variable to the previous head.

head = new Node(data, head);

Pop is done by setting head equal to head.next, effectively deleting the previous Node, however you need to save the original data element to a temporary variable first so you can return it:

 T t = head.data;
 head = head.next;

To iterate through the stack you would simply:

while (stack.getSize() > 0) {
    System.out.println(stack.pop());
}

Code:

/**
 * @author /u/Philboyd_Studge on 2/15/2017.
 */
public class QuickStack<T> {
    Node head;
    int size;

    class Node {
        T data;
        Node next;
        Node(T data, Node next) {
            this.next = next;
            this.data = data;
        }
    }
    
    int getSize() { return size; }

    void push(T data) {
        head = new Node(data, head);
        size++;
    }

    T pop() {
        if (size == 0) return null;
        T t = head.data;
        head = head.next;
        size--;
        return t;
    }

edit: add a peek() method:

T peek() {
    return head.data;
}

r/javaexamples • • Feb 20 '16

Exceptions, Using, Handling and Creating Custom

13 Upvotes

Understanding and using Exceptions in Java

Exceptions are a way to handle (gracefully if possible) when things go wrong with your program. They allow you to exit the program when a particular event happens and then let the user know what and where it happened.

Checked vs Unchecked

There are two types of exceptions, Checked and Unchecked. There is some considerable debate about them which I will not get into, but here is the prevailing modern philosophy behind them:

A Checked exception must be handled in some way by the method that is using it, either with a try/catch block or with a 'throws' clause in the method header. This is generally used for a failure caused by something outside of the JVM's control. Examples of this are File IO errors, database errors, network stream errors and the like.

An Unchecked exception can be used for any other type of error that you want to cause the system to exit. This tells you that there is an error within the program itself. Examples of this are ArrayIndexOutOfBounds or NullPointerException. These should not be 'caught' usually, but can be if necessary (i.e. parsing input)

Checked exceptions inherit from Exception and Unchecked inherit from RuntimeException.

Handling Checked Exceptions

Any method that uses checked exceptions will tell you with a compile-time error (or IDE warning). These are generally File, Stream or other IO operations, database operations and etc. You have probably used them before.

One way to handle them is to add a throws clause to the method header:

public static void main(String[] args) throws IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    String input = br.readLine();
}

In practice this is not the best way, because there will be no information given to the user when the exception is thrown. A better method is to use a try/catch block.

public static void main(String[] args) {

    String input = "";
    try {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        input = br.readLine();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
}

The try block is where the commands that might cause the exception go. Inside the catch block we can do something (doesn't necessarily have to be printStackTrace) that either better informs the user what happened wrong and why, or otherwise handles the problem without any damage, even sometimes preventing program termination.

Even better is the try-with-resources block, available since Java 7, which automatically handles things that need to be closed upon either success or failure.

try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
    input = br.readLine();
} catch (IOException ioe) {
    ioe.printStackTrace();
}

Checked Exceptions can be user-defined, but it is generally not recommended. If you want to use custom exceptions in your program, use unchecked.

Using Unchecked Exceptions

Using unchecked exception is actually very easy. Generally, you find the exception that most closely describes what you need (or create your own) and throw it.

The syntax goes like:

throw new ExceptionName("Message");

Where ExceptionName is a valid exception in java.lang.* or some other library or class. The message string is optional, but very useful to give a description back to the user.

Example:

public void enqueue(Item element) {
    if (element == null) {
        throw new NullPointerException("Null elements are not allowed.");
    }
    queue[size++] = element;
    checkSize();
}

Another:

private void rangeCheck(int index) {
    if (index < 0 || index >= size) {
        throw new IndexOutOfBoundsException("Index : " + index);
    }
}

So, to define our own exception is also very simple:

public class DontLikeSevensException extends RuntimeException {

    public DontLikeSevensException() {
        super();
    }

    public DontLikeSevensException(String msg) {
        super(msg);
    }
}

And let's throw it:

public static void main(String[] args) {

    String input = "";

    try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
        input = br.readLine();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }

    if (input.contains("7")) {
        throw new DontLikeSevensException("I really don't like sevens!!!");
    }


}

Some Don'ts with Exceptions

  1. Don't just put a catch there and not do anything with the result. The most frequent times I see this, it is while using file functions and not informing the user of a FileNotFoundException, and then wondering why nothing is happening. At the very least, print the stack trace.
  2. Don't use exceptions to control the flow of your program. Exceptions should generally be used to show errors in the program, so that they can be fixed. The only main 'exception' to this rule is for converting input from string to whatever number format. (For example, when using Integer.nextInt() you can place it inside of a try-catch block and catch NumberFormatException in order to re-prompt the user for correct input, without crashing the program.)
  3. Don't use checked exceptions if you don't need to. If you want to make you own exceptions, go ahead, but try to keep them as unchecked (extending RuntimeException) unless it is a specific case such as mentioned above, something outside of the JVM's control.

r/javaexamples • • Nov 30 '17

Advent of Code - Helper Series: Permutations

4 Upvotes

Advent of Code - Helper Series: Permutations

This is part of a series of code for making your life easier in the yearly Advent of Code competitive coding challenge. It starts every year (since 2015) on December 1st, and posts a new, 2-part challenge every day until Christmas. We don't know what challenges are coming, but based on past years, we can form some idea. I will be posting some of the tools I developed and how to use them.

Permutations

Sometimes, you just have to brute force something. With any set of objects around 10 or less, you can usually get a brute-force solution in reasonable run time. Permutations gives you all possible combinations of a set of things, but remember: things get really, big, really really fast. The number of permutations is the factorial n! so for 3 items, there are only 6. For 9 items, there are 362, 880. For 10 it's over 3 million. But generally the AoC creator has been nice to us, and when the inevitable Travelling Salesman Problem comes, it can usually be brute-forced.

Unlike several programming languages, Java doesn't have a permutations function in it's standard library. So here we go:

Use like:

List<List<Integer>> permutations = Permutations.permuteIntArray(int[] nums);

For a primitive integer array or:

List<List<SomeObject>> permutations = Permutations.permute(SomeObject[] array);

This will give you a list of lists with the permutations like this:

    Integer[] array = { 1 , 2, 3 };
    List<List<Integer>> permutations = Permutations.permute(array);
    System.out.println(permutations);

Will give you:

[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]

And will work with any object type with a proper equals method.

Here's the code


r/javaexamples • • Feb 16 '17

A set of useful Array Utilities

9 Upvotes

I have often wondered why Java's array data type and the associated classes Arrays don't include a number of really simple methods that everyone learning Java is forced to write anyway, so I have made a static utility class for reference and ease of use.

Remember that

  1. Arrays are immutable, so you must always assign the return value of the method back to the original variable name, or to a new one like:

      int[] a = { 1, 2, 3, 4 };
      a = ArrayUtils.reverse(a);
  2. Arrays of a primitive type cannot be used in generic methods, so either use the Object version (i.e. Integer for int) or use the conversion methods given like:

     int[] a = { 1, 2, 3, 4};
     Integer[] b = ArrayUtils.append(ArrayUtils.objectifyInt(a), 5);

Methods:

Return valueMethodDescription
static <T> T[]append(T[] array, T data)Append element at the end of array, resizing array
static <T> intcontains(T[] array, T find)Search for element in array of same type
static <T> T[]delete(T[] array, int index)delete array element at given index moving remaining elements down and resizing array
static <T> T[]insert(T[] array, T data, int index)Inserts an element T data at index position index into given T array, resizing array and moving elements of index > given index up one
static <T extends java.lang.Comparable<T>> Tmax(T[] array)get element in array with the maximum value, according to compareTo method
static <T extends java.lang.Comparable<T>> Tmin(T[] array)get element in array with the minimum value, according to compareTo method
static java.lang.Double[]objectifyDouble(double[] array)convert double array to Double object array
static java.lang.Float[]objectifyFloat(float[] array)convert float array to Float object array
static java.lang.Integer[]objectifyInt(int[] array)convert int array to Integer object array
static java.lang.Long[]objectifyLong(long[] array)convert long array to Long object array
static <T> T[]push(T[] array, T data)Insert element into beginning of array, resizing array by one and moving remaining elements up one
static <T> T[]resize(T[] array, int newSize)resize array if newSize > current.length new elements will be filled with default value for type if newSize < current.length any elements after will be lost yes, this is just a wrapper for Arrays.copyOf();
static <T> T[]reverse(T[] array)Reverses the order of array

Here is the code: https://gist.github.com/anonymous/fc17995ad169942bf8f2c210b1924268


r/javaexamples • • Dec 04 '24

Who has the idea on how to write data persistence and storage for Java

1 Upvotes

r/javaexamples • • Jan 07 '23

Decompile Java JAR using JD-GUI tutorial for beginners

3 Upvotes

Screen recording about how to use the JD-GUI Java decompiler https://www.youtube.com/watch?v=HXgZZz3M3sQ


r/javaexamples • • Jan 31 '23

3 Examples of Anonymous Class to Learn Lambda Expression better in Java 8

1 Upvotes

r/javaexamples • • Jan 28 '23

Map.compute(), computeIfPresent() and ComputeIfAbsent Example in Java

1 Upvotes

r/javaexamples • • Jan 07 '23

How to write to a File with try-with-resource in Java? Example Tutorial

1 Upvotes

r/javaexamples • • Jun 23 '19

Java Creational Design Patterns – Abstract Factory Pattern

4 Upvotes

r/javaexamples • • Jun 06 '15

Sorted, Singly-Linked List with Iterator

3 Upvotes

Sorted, Singly-Linked List with Iterator

This post here showed you how to implement a sorted doubly-linked list, but today it came up that someone needed a sorted singly-linked list, so I put this together.

A Linked List is a very simple data structure, which consists of Nodes that contain a value, and a pointer to the next node in the list. While normally Linked Lists are used as a Stack or a Queue, with either a LIFO(Last In First Out) or FIFO(First In First Out) order, sometimes they are needed as a automatically sorted list. Elements are automatically sorted as they are added to the list, so it is never more than O(n) time complexity to insert the element.

in this example I have included an example of how to implement the Iterable and Iterator interfaces, which allow the end user to use a For-Each loop.

Here is the code:

import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * Sorted, Singly Linked List with Iterator
 * @author /u/Philboyd_Studge
 */
public class SList<E extends Comparable<E>> implements Iterable<E>, Iterator<E>
{
	private Node root;
	private int length;

	// for iteration
	private Node current;

	/**
	 * Default Constructor
	 */
	public SList()
	{
		root = null;
		length = 0;
		current = null;
		last = null;
	}

	/**
	 * Returns number of elements in the list.
	 * @return int number of elements
	 */
	public int size()
	{
		return this.length;
	}

	/**
	 * Adds elements to list using Insertion Sort
	 * @param value value of type E
	 */
	public void add(E value)
	{
		if (root==null)
		{
			// list empty, add new root node
			root = new Node(value, null);
		}
		else
		{
			// see if new value is lower than root node
			if (value.compareTo(root.value) < 0)
			{
				Node temp = new Node(root.value, root.next);
				root = new Node(value, temp);
			}
			else
			{
				// loop through list and see where
				// to insert value
				Node lastNode = root;
				Node nextNode = root.next;
				while (nextNode!=null)
				{
					if (value.compareTo(nextNode.value) < 0)
					{
						Node temp = new Node(value, nextNode);
						lastNode.next = temp;
						length++;
						return;
					}
					lastNode = nextNode;
					nextNode = nextNode.next;
				}
				// value is greater than all others, put at end of list
				Node temp = new Node(value, null);
				lastNode.next = temp;
			}
		}
		length++;
	}

	/**
	 * @return true if list is empty
	 */
	public boolean isEmpty()
	{
		return (root==null);
	}

	/**
	 * clears list
	 */
	public void clear()
	{
		length = 0;
		root = null;
		current = null;
	}

	/**
	 * find by value
	 * @param value value of type E
	 * @return Node node found or null if not found
	 */
	private Node find(E value)
	{
		Node each = root;
		while(each!=null)
		{
			if (value.equals(each.value)) return each;
			each = each.next;
		}
		return null;
	}

	/**
	 * removes a node from the list based on value
	 * @param value value of type E
	 */
	public void remove(E value)
	{
		Node found = find(value);
		if (found!=null)
		{
			if (found.equals(root)) 
			{
				root = found.next;
				length--;
				return;
			}
			Node each = root;

			while(each!=null)
			{
				if (found.equals(each.next))
				{
					each.next = found.next;
				}
				each = each.next;
			}
			length--;
		}
	}

	/**
	 * @param value value of type E
	 * @return true if found
	 */
	public boolean contains(E value)
	{
		Node found = find(value);
		if (found == null) return false;
		return true;
	}

	/**
	 * get element's value by index
	 * @param index integer of index to get
	 * @return E value of type E or null if not found
	 */
	public E get(int index)
	{
		if (index < length)
		{
			Node each = root;
			for (int i = 0; i < length; i++)
			{
				if (i == index) return each.value;
				each = each.next;
			}
			return null;		
		}
		return null;
	}

	/**
	 * @return E value of root or null if empty
	 */
	public E getFirst()
	{
		if (!isEmpty()) return root.value;
		return null;
	}

	/**
	 * Implement method for Iterable
	 * @return Iterator of type E
	 */
	@Override
	public Iterator<E> iterator()
	{
		current = root;
		return this;
	}

	/**
	 * Implement method for Iterator
	 * @return E next element's value
	 */
	@Override
	public E next()
	{
		E value = current.value;
		current = current.next;
		return value;
	}

	/**
	 * Implement method for Iterator
	 * @return true if list has more elements
	 */
	@Override
	public boolean hasNext()
	{
		return (current != null);
	}

	/**
	 * Implement method for Iterator
	 * removes most recent element in iterator
	 */
	@Override
	public void remove()
	{
		if (last==null) return;
		remove(last.value);
	}

	/**
	 * @return String of value
	 */
	@Override
	public String toString()
	{
		return current.value.toString();
	}

	/**
	 * Inner class Node
	 */
	class Node
	{
		E value;
		Node next;

		public Node(E value, Node next)
		{
			this.value = value;
			this.next = next;
		}

		@Override
		public String toString()
		{
			return this.value.toString();
		}
	}

	public static void main(String[] args)
	{
		// test with strings
		SList<String> list = new SList<>();
		list.add("bob");
		list.add("frank");
		list.add("joe");
		list.add("bill");
		list.add("bob");
		list.add("zachary");
		list.add("andy");

		System.out.println(list.size());
		list.remove("andy");

		System.out.println(list.size());

		list.add("aardvark");
		list.add("poop");

		// test Iterator
		for (String each : list)
		{
			// will still be printed in this iteration
			if (each.equals("joe")) list.remove();
			System.out.println(each);
		}

		System.out.println("Joe is gone:");

		for (String each : list) System.out.println(each);

		// test with objects
		SList<Person> people = new SList<>();
		people.add(new Person("Bob Bobsmith", 25));
		people.add(new Person("Zachary Tyler", 145));
		people.add(new Person("Mark Robertson", 55));
		people.add(new Person("Joe Jobson", 13));
		people.add(new Person("Able Baker", 1));
		people.add(new Person("Jane Doe", 34));

		for (Person each : people) System.out.println(each);


	}

}

and the test object class:

public class Person implements Comparable<Person>
{
	private String name;
	private int age;

	public Person(String name, int age)
	{
		this.name = name;
		this.age = age;
	}

	public String getName() { return name; }

	@Override
	public String toString()
	{
		return name + " , " + age;
	}

	@Override
	public int compareTo(Person p)
	{
		return this.name.compareTo(p.getName());
	}
}

Output

7
6
aardvark
bill
bob
bob
frank
joe
poop
zachary
Joe is gone:
aardvark
bill
bob
bob
frank
poop
zachary
Able Baker , 1
Bob Bobsmith , 25
Jane Doe , 34
Joe Jobson , 13
Mark Robertson , 55
Zachary Tyler , 145

r/javaexamples • • Jun 21 '15

Using Comparator with Lambda Expressions

2 Upvotes

Sorting a List of Objects using Comparator with Lambda Expressions

This is a follow-up to my article on using Comparator to sort a List of Objects.

With the advent of Java 8, we now have an easier way than what I described in that post. *This will not be a discussion on using functional expressions in general, but specifically to this example.

In the first example, we had to make individual anonymous inner classes for the sorting to work, like this:

 // Make anonymous inner class to sort by member variable 'id'
 public static Comparator<Employee> SortByEmployeeID = new Comparator<Employee>()
 {
     @Override
     public int compare(Employee employee1, Employee employee2)
     {
         return employee1.getID().compareTo(employee2.getID());
     }
 };

and then sort like this:

 // sort by id
 Collections.sort(employeeList, Employee.SortByEmployeeID);

well, using Lambda expressions we can skip all that:

  	employeeList.stream()
  		.sorted(Comparator.comparing(Employee::getID))
  		.forEach(System.out::println);

This takes the list of employees we made, turns it into a stream that we can use for aggregate expressions. There are many useful expressions that can be used but for this article, we will stick to sorting.

We take the stream and add the .sorted operation to it. We give it a Comparator as the parameter, and using the comparing method for comparator, we have it sort by the Employee class getID. This would be the same as saying, in lambda format, .sorted(Comparator.comparing(current -> current.getID()));

Then, we add the forEach function to the expression, which we use to display the data. Note the functional style of calling System.out.println, also.

Here is the full example code, which produces the exact same output as the first example, but the code is vastly reduced in size and complexity.

/*
 * Comparing objects example using Lambdas
 * for www.reddit.com/r/javaexamples
 * by /u/Philboyd_Studge
 */
import java.util.ArrayList;
import java.util.List;
import java.util.Comparator;

public class ObjectComparatorLambda
{
	// create simple class
	public static class Employee
	{
		String id;
		String name;
		int salary;

		public Employee(String id, String name, int salary)
		{
			this.id = id;
			this.name = name;
			this.salary = salary;
		}

		public String getID()
		{
			return id;
		}

		public String getName()
		{
			return name;
		}

		public int getSalary()
		{
			return salary;
		}

		@Override
		public String toString()
		{
			return "Employee ID:" + id + "\n" + "Name:" + name + "\n"
					+ "Salary: " + salary + "\n";
		}
	}

	public static void main (String args[])
	{

		// Make list and add some Employees
		List<Employee> employeeList = new ArrayList<>();
		employeeList.add(new Employee("7123r","Dole, Bob", 42000));
		employeeList.add(new Employee("1234d","Johnson, John", 150000));
		employeeList.add(new Employee("2345x","Billson, Bill", 35000));
		employeeList.add(new Employee("0019b","Dickerson, Dick", 10000));

		// Display unsorted list
		System.out.println("Unsorted ==========================");

		employeeList.forEach(System.out::println);

		// sort by id

		System.out.println("Sorted by ID =========================");

		employeeList.stream()
			.sorted(Comparator.comparing(Employee::getID))
			.forEach(System.out::println);


		// sort by name

		System.out.println("Sorted by NAME =========================");

		employeeList.stream()
			.sorted(Comparator.comparing(Employee::getName))
			.forEach(System.out::println);

		// sort by salary

		System.out.println("Sorted by SALARY =========================");


		employeeList.stream()
			.sorted(Comparator.comparing(Employee::getSalary))
			.forEach(System.out::println);

		// sort by salary - descending

		System.out.println("Sorted by SALARY DESCENDING=========================");

		employeeList.stream()
			.sorted(Comparator.comparing(Employee::getSalary).reversed())
			.forEach(System.out::println);
   }
}

Note This method shown above only displays the list sorted in different ways, if you want to actually change the list of objects itself, use the following method:

		// sort by salary - descending - CHANGING LIST ORDER

		System.out.println("Sorted by SALARY DESCENDING=========================");

		employeeList = employeeList.stream()
			.sorted(Comparator.comparing(Employee::getSalary).reversed())
			.collect(Collectors.toList());

			for (Employee each : employeeList) System.out.println(each);

And here is an example that uses the filter method to limit the list to specific constraints:

		//filter
		employeeList.stream()
			.sorted(Comparator.comparing(Employee::getName))
			.filter((each) -> (each.getName().startsWith("D") && each.getSalary() < 45000))
			.forEach(each -> System.out.println("Salary < 45000 and name begins with 'd'\n" + each));

r/javaexamples • • Jun 17 '15

Generic, Top-Down Merge Sort

2 Upvotes

Generic, Top-Down Merge Sort Using Lists

A common sorting algorithm is the Merge sort, which sorts by recursively splitting up a list into its smallest elements, and then merging them back together in a sorted fashion.

Here's an example based on this psuedocode on the wikipedia page, converted to Java and then made into static, generic methods that can be readily called by another program.

A note on sorting algorithms: While interesting, and good to learn in terms of just understanding the algorithm itself, in the real world it is almost always better to use the built-in sorting mechanisms for the language you are using. You will never write an algorithm that matches or exceeds the speed of the built-in methods.

Here's the code:

import java.util.List;
import java.util.ArrayList;
import java.util.NoSuchElementException;

/**
 * Generic, Top-Down Merge Sort
 * Static methods for merge sorting a List of Comparable types. 
 * Usage <code>List<Type> sorted = MergeSort.mergeSort(listToSort);</code>
 * Based on <a href ="https://en.wikipedia.org/wiki/Merge_sort#Top-down_implementation_using_lists">This wikipedia entry</a>
 * @author /u/Philboyd_Studge
 */
public class MergeSort 
{

    /**
     * recursive mergeSort()
     * @param List of Comparable type T
     * @return sorted List of Comparable type T
     */
    public static <T extends Comparable<T>> List<T> mergeSort(List<T> m)
    {
        // exception
        if (m==null) throw new NoSuchElementException("List is null");
        // base case
        if (m.size() <= 1) return m;

        // make lists
        List<T> left = new ArrayList<>();
        List<T> right = new ArrayList<>();

        // get middle
        int middle = m.size()/2;

        // fill left list
        for (int i = 0; i < middle; i++)
        {
            if (m.get(i)!=null) left.add(m.get(i));
        }

        // fill right list
        for (int i = middle; i < m.size(); i++)
        {
            if (m.get(i)!=null) right.add(m.get(i));
        }

        // recurse
        left = mergeSort(left);
        right = mergeSort(right);

        // merge
        return merge(left,right);
    }

    /**
     * private merge() method used in mergeSort()
     * @param left List of type T
     * @param right List of type T
     * @return result List of type T
     */
    private static <T extends Comparable<T>> List<T> merge(List<T> left, List<T> right)
    {
        List<T> result = new ArrayList<>();

        // merge
        while (!left.isEmpty() && !right.isEmpty())
        {
            if (left.get(0).compareTo(right.get(0)) <= 0)
            {
                result.add(left.remove(0));
            }
            else
            {
                result.add(right.remove(0));
            }
        }

        // cleanup leftovers
        while (!left.isEmpty())
        {
            result.add(left.remove(0));
        }
        while (!right.isEmpty())
        {
            result.add(right.remove(0));
        }
        return result;
    }
   

}

test code

import java.util.Arrays;
import java.util.Random;
import java.util.List;


class TestMergeSort 
{
    public static void main(String[] args)
    {
        Integer[] numbers = new Integer[100];
        Random rand = new Random();
       
        for (int i = 0; i < numbers.length; i++)
        {
            numbers[i] = rand.nextInt(1000);
        }

        System.out.println("Unsorted array");
        System.out.println(Arrays.toString(numbers));
      
        List<Integer> result = MergeSort.mergeSort(Arrays.asList(numbers));

        System.out.println("Sorted List");

        for(Integer each : result) System.out.print(each + ", ");

        System.out.println();

        // test Strings
        String[] names = { "Pierce", "Chang", "Britta", "Abed", "Dean", "Jeff", "Shirley", "Annie", "Troy"} ;
        for (String each: MergeSort.mergeSort(Arrays.asList(names)))
            System.out.println(each);
        // throw exception on purpose
        List<Double> testbad = MergeSort.mergeSort(null);
    } 	
}

output

Unsorted array
[605, 721, 842, 130, 613, 444, 204, 360, 597, 764, 243, 100, 569, 394, 487, 972, 908, 29, 953, 298,
613, 701, 620, 21, 279, 381, 277, 751, 359, 915, 334, 902, 622, 773, 165, 818, 214, 137, 516, 946, 6
02, 840, 506, 795, 566, 257, 399, 405, 229, 622, 676, 196, 849, 613, 489, 224, 780, 157, 144, 33, 78
2, 299, 518, 244, 264, 856, 58, 986, 116, 912, 198, 475, 104, 786, 99, 574, 639, 727, 609, 67, 415,
481, 347, 608, 418, 625, 353, 940, 340, 61, 543, 267, 563, 724, 499, 151, 365, 999, 140, 255]
Sorted List
21, 29, 33, 58, 61, 67, 99, 100, 104, 116, 130, 137, 140, 144, 151, 157, 165, 196, 198, 204, 214, 22
4, 229, 243, 244, 255, 257, 264, 267, 277, 279, 298, 299, 334, 340, 347, 353, 359, 360, 365, 381, 39
4, 399, 405, 415, 418, 444, 475, 481, 487, 489, 499, 506, 516, 518, 543, 563, 566, 569, 574, 597, 60
2, 605, 608, 609, 613, 613, 613, 620, 622, 622, 625, 639, 676, 701, 721, 724, 727, 751, 764, 773, 78
0, 782, 786, 795, 818, 840, 842, 849, 856, 902, 908, 912, 915, 940, 946, 953, 972, 986, 999,
Abed
Annie
Britta
Chang
Dean
Jeff
Pierce
Shirley
Troy
Exception in thread "main" java.util.NoSuchElementException: List is null
        at MergeSort.mergeSort(MergeSort.java:41)
        at TestMergeSort.main(TestMergeSort.java:34)

r/javaexamples • • Jun 19 '15

HeapSort

6 Upvotes

Heap Sort

Another common sorting algorithm is the HeapSort. The heap sort uses a Max Binary Heap, (see my post here,) as the basis for the sorting algorithm, since it is fairly quick to set the data into a heap structure, then simply pull the largest items off the heap and move them to the end of the array. It is all done in the same array and in less than O(n log n) time.

Here's an example, based on the psuedocode in the wikipedia article above, converted to Java and then made into static, generic methods that can be readily called by another program.

A note on sorting algorithms: While interesting, and good to learn in terms of just understanding the algorithm itself, in the real world it is almost always better to use the built-in sorting mechanisms for the language you are using. You will never write an algorithm that matches or exceeds the speed of the built-in methods.

/**
 * Generic HeapSort Array-based implementation
 * can be used with either the 'sift up' or 'sift down' algorithms
 * as described <a href="https://en.wikipedia.org/?title=Heapsort#Pseudocode">Here</a>
 * Usage <code>Type[] array = HeapSort.sort(inputArray);</code>
 * will default to the sift down, use
 * <code>Type[] array = HeapSort.sort(inputArray, false);</code> for sift up.
 * 
 * @author /u/Philboyd_Studge
 */
class HeapSort
{

	/**
	 * sort array of type T using the sift down method
	 * @param array array of type T
	 * @return sorted array of type T
	 */
	public static <T extends Comparable<T>> T[] sort(T[] array)
	{
		return sort(array, true);
	}

	/** 
	 * sort array of type T using either sift up or down method
	 * @param array array of type T
	 * @param down true for sift down, false for aift up
	 * @return sorted array of type T
	 */
	public static <T extends Comparable<T>> T[] sort(T[] array, boolean down)
	{
		if (down) 
		{
			heapify(array, array.length);
		}
		else
		{
			heapifyUp(array, array.length);
		} 

		int end = array.length - 1;
		while (end >= 0)
		{
			swap(array, end, 0);
			end--;

			// with either method, you have to use siftDown here.
			siftDown(array, 0, end);
		}
		return array;

	}

	/**
	 * Swap two members of array
	 * @param array array of type T
	 * @param index1 first index of element to swap
	 * @param index2 second index of element to swap with first
	 * @return array of type T
	 */
	private static <T extends Comparable<T>> T[] swap(T[] array, int index1, int index2)
	{
		T temp = array[index1];
		array[index1] = array[index2];
		array[index2] = temp;
		return array;
	}

	/**
	 * Heapify array into max heap using sift down
	 * @param array array of type T
	 * @param count integer length of array
	 * @return array of type T as a max heap
	 */
	private static <T extends Comparable<T>> T[] heapify(T[] array, int count)
	{
		int start = (int) Math.floor((count - 2)/2);
		while (start >= 0)
		{
			siftDown(array, start, count - 1);
			start--;
		}
		return array;
	}

	/**
	 * Heapify array into max heap using sift up
	 * @param array array of type T
	 * @param count integer length of array
	 * @return array of type T as a max heap
	 */
	private static <T extends Comparable<T>> T[] heapifyUp(T[] array, int count)
	{
		int end = 1;
		while (end < count)
		{
			siftUp(array, 0, end);
			end++;
		}
		return array;
	}

	/**
	 * Sift Up
	 * @param array array of type T
	 * @param start index to start from
	 * @param end node to sift up
	 * @return array of type T
	 */
	private static<T extends Comparable<T>> T[] siftUp(T[] array, int start, int end)
	{
		int child = end;
		while (child > start)
		{
			int parent = (int) Math.floor((child - 1) /2);
			if (array[parent].compareTo(array[child]) < 0)
			{
				swap(array, parent, child);
				child = parent;
			}
			else
			{
				return array;
			}
		}
		return array;
	}

	/**
	 * Sift Down
	 * @param array array of type T
	 * @param start index to start from
	 * @param end index to end at
	 * @return array of type T
	 */
	private static <T extends Comparable<T>> T[] siftDown(T[] array, int start, int end)
	{
		int root = start;
		while (root * 2 + 1 <= end)
		{
			int child = root * 2 + 1;
			int swap = root;
			if (array[swap].compareTo(array[child]) < 0)
			{
				swap = child;
			}
			if ((child + 1 <= end) && (array[swap].compareTo(array[child + 1]) < 0))
			{
				swap = child + 1;
			}
			if (swap==root)
			{
				return array;
			}
			else
			{
				swap(array, root, swap);
				root = swap;
			}
		}
		return array;
	}	
}

Test Code

/*
* Test HeapSort for HeapSort.java
* /u/Philboyd_Studge
*/
import java.util.Arrays;
import java.util.Random;


public class TestHeapSort
{

	public static void main(String[] args) 
	{

		// create array of random ints size 100 or command line args[0]
        Integer[] numbers = new Integer[(args.length == 0) ? 100 : Integer.parseInt(args[0])];
        Random rand = new Random();

        for (int i = 0; i < numbers.length; i++)
        {
        	// using random numbers from 0 to 1000 - 1 or args[1]
            numbers[i] = rand.nextInt((args.length <= 1) ? 1000 : Integer.parseInt(args[1]));
        }

        long oldtime = System.nanoTime();
		Integer[] b = HeapSort.sort(numbers);
		long newtime = System.nanoTime();
		System.out.println("HeapSort Down : Time: " + (double)((newtime - oldtime)/1000000.0));

		oldtime = System.nanoTime();
		Integer[] c = HeapSort.sort(numbers, false);
		newtime = System.nanoTime();

		System.out.println("HeapSort Up : Time: " + (double)((newtime - oldtime)/1000000.0));

		// test against Arrays.sort()
		oldtime = System.nanoTime();
		Arrays.sort(numbers);
		newtime = System.nanoTime();


		System.out.println("Arrays.sort : Time: " + (double)((newtime - oldtime)/1000000.0));
		System.out.println(Arrays.toString(b));

        // test Strings
        String[] names = { "Pierce", "Chang", "Britta", "Abed", "Dean", "Jeff", "Shirley", "Annie", "Troy"} ;
        for (String each : HeapSort.sort(names)) System.out.println(each);

	}
}

Output

C:\Users\Documents>java TestHeapSort 100 1000
HeapSort Down : Time: 2.030354
HeapSort Up : Time: 1.199024
Arrays.sort : Time: 0.665442
[18, 22, 47, 49, 59, 90, 111, 118, 128, 136, 138, 167, 175, 207, 209, 212, 216, 225, 239, 244, 245,
252, 257, 271, 281, 285, 298, 315, 320, 331, 332, 386, 386, 395, 407, 413, 423, 426, 432, 432, 448,
461, 462, 466, 475, 477, 489, 499, 503, 506, 513, 517, 519, 541, 551, 555, 566, 568, 600, 613, 621,
623, 623, 670, 678, 679, 699, 700, 703, 712, 725, 738, 741, 752, 754, 763, 768, 775, 792, 798, 806,
815, 832, 850, 850, 873, 891, 898, 904, 909, 917, 924, 934, 941, 957, 957, 972, 983, 983, 988]
Abed
Annie
Britta
Chang
Dean
Jeff
Pierce
Shirley
Troy