r/javaexamples • • May 09 '22

JKagu, open source select/replace text software

2 Upvotes

Hello all,

I developed a program called JKagu, from which you can see the repository here: https://github.com/LevelUp8/JKagu

I am a long time java web developer (more than 8 years) and from time to time I wish to have an advanced select and replace text software.

I am aware that there are already solutions, but many of them didn't do all the things that I wanted, the way I wanted. Most of them I had to research about regex expressions and so on.

Long story short, I made a software that helps me with my work and I decided to share it as an open source project. Anyway, if it can help several more people, I think it was worth it.

It is a Java FX GUI program what works on Windows and Linux. It is row based and it is not a traditional text editor like notepad++ because I wanted to manage to read and perform operations on a big amount of data. I tested it with 120 000 rows and it performed ok.

Please visit the wiki https://github.com/LevelUp8/JKagu/wiki for more information.

Have a great day!

Best regards,

LevelUp


r/javaexamples • • Feb 11 '22

3 ways to convert String to JSON object in Java? Examples

2 Upvotes

r/javaexamples • • Dec 31 '20

JavaFX Spelling Test Application packaged for deployment

2 Upvotes

Showcasing a finished JavaFX application called SpellFX. This is a Spelling Test application for parents and children to use to practice their spelling. The video demonstrates the finished product in action and then looks at how the application is installed and finally shows the installer experience.

https://youtu.be/IabhZfLIRr4


r/javaexamples • • Sep 14 '20

How to decompile .jar file or .class file? | Java Decompilers & eclipse ...

2 Upvotes

r/javaexamples • • Mar 19 '20

Getting Started With JTree

2 Upvotes

Now unlike some of the more basic swing objects, JTree is designed to display a tree structure, another object is used to hold the data which determines what JTree displays.

This other object is the TreeModel. Now that is not to say that you have to use a model to get JTree to display something, you don’t and we can take a look at that in a while.

https://softwarepulse.co.uk/blog/getting-started-with-jtree-part-1/


r/javaexamples • • Oct 22 '19

Java Creational Design Patterns – Prototype Pattern with Sample Code

2 Upvotes

Prototype pattern comes under creational design pattern. As we know, in Java object creation process is time consuming and costly, so instead of creating object every time we can create copy of existing object. So using this design pattern we can create object in easiest way. In prototype pattern object cloning is used to create object copies, which is implemented using clone() method.

You can use this pattern if any of the below point applies-

  • the client application wants to avoid subclasses of an object creator

  • in your application you find using ‘new’ keyword to create object pretty expensive.

Prototype pattern doesn’t create new object it just create clone of it. It takes all the necessary data and stored data in memory and whenever new object is required, prototype pattern creates clone of the object and can be customized later.

Prototype Pattern by Example

https://www.opencodez.com/java/prototype-pattern.htm


r/javaexamples • • Oct 11 '19

RxJS Subject in depth – Multicast values [Article]

2 Upvotes

r/javaexamples • • May 05 '19

Java concurrent API - CyclicBarrier

2 Upvotes

Quick overview of Java Cyclic barrier with code examples.

Java CyclicBarrier


r/javaexamples • • Dec 15 '18

Two more common Java problems (hiding, for-each changes)

2 Upvotes

1. inadvertent hiding

You make a ball that you move around on the screen:

class Ball {
    int x, y, width, height;
    int xspeed = 3; //in pixels
    int yspeed = 3;
    
    Ball() {
       x=100;
       y=100;
       ...
    }

    void move() { ... }
} 

Later on you want to make it collide with another ball or some object, so you make it a Rectangle which lets you use the Rectangle class method .intersects()

class Ball extends Rectangle {
    int x, y;
    int xspeed = 3; //in pixels
    ...

Problem
The Rectangle's x,y,width,height, variables are hidden by the variables in this subclass. Thus .intersects() will never work.

Solution
Delete the line int x, y, width, height; so that when you set values for these variables, you're setting the Rectangle class values


2. Changing objects in a for-each loop

Consider the code below: It creates 5 items, tries to change them, and then prints them out.

NOTE
When using a for-each loop, you can change the property of an item in the loop, but you cannot change the item itself. I don't know why this is. If you want to change the item itself, you have to use a regular for loop with .get() and .put().
You can change the name of item 3, but you cannot change the whole item 2 to be recreated with 99.

import java.util.ArrayList;

public class ForEach {

	public static void main(String[] args) {
		ArrayList<Item> items = new ArrayList<Item>();
		//create items
		for (int i = 0; i < 5; i++) {
			items.add(new Item(i));
		}
		//try and modify using for each loop
		for (Item z : items) {
			if (z.n == 2) z = new Item(99);
			if (z.n == 3) z.name = "Three";			
		}
		//print items
		for (Item z : items) {
			System.out.println(z.n + "=" + z.name);
		}
	}
	
	static class Item {
		String name = "blank";
		int n;

		Item(int n) {
		     this.n=n;
		} 
	}

}

/* Printout:
	0=blank
	1=blank
	2=blank
	3=Three
	4=blank
*/

r/javaexamples • • Sep 30 '18

Learn how to perform Linear Regression in Java!!

2 Upvotes

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 • • 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 • • Aug 23 '17

Client Server Communication

2 Upvotes

Hello guys this is an example of Client Server communication using threads. https://bittlife.com/server-client-communication-using-java/


r/javaexamples • • Jul 31 '17

Spring Data REST and Projections

2 Upvotes

My final post in my series on Spring Data REST -

https://www.javabullets.com/spring-data-rest-projections/

My aim is to reach some conclusions about when to use Spring Data REST


r/javaexamples • • Jun 15 '17

Data Hiding using JsonIgnore and Spring Data JPA

2 Upvotes

Heres my latest tutorial on Spring Data JPA -

https://www.javabullets.com/data-hiding-using-jsonignore-spring-data-jpa/

My approach is to keep it concise, and try to provide a working example.

But let me know any feedback


r/javaexamples • • Jun 06 '17

Securing Spring Data REST with PreAuthorize

2 Upvotes

My latest blog post on Securing Spring Data REST -

Securing Spring Data REST with PreAuthorize


r/javaexamples • • Apr 03 '17

[Intermediate] Annotations & Reflection: Designing a CSV-to-Object Deserializer

2 Upvotes

Annotations and Reflection

This week we are going to learn about using Java's Annotations and Reflection APIs, which are a way to use and control classes in ways that you couldn't normally with regular Java commands. You might be familiar with annotations like @Override or @Deprecated which are more of just 'hints' to the compiler, but you can create your own annotations which can be used during runtime. You might have used these with FXML or Spring or many other frameworks.

Reflection methods allow you to inspect Class information during runtime. It gives you access to all sorts of information about the class, such as Methods, Constructors, Fields and even Local Variables. It will even let you get and set Field values, and create instances of the class. I would recommend looking over some of the online tutorials, including Jenkov's excellent series here, as I will mainly be describing the methods used to build our tutorial example.

What we are going to use these methods for is to build a CSV-to-Object deserializer.

CSV

CSV files, meaning comma-separated-values is a common type of file containing tabular data. It is a regular text file where every line is a 'record' of data, and each line contains individual items of data separated by commas. There is usually no indication given as to the data type of the items, and may contain a header line, also delimited with commas, with column names. Sometimes the data items are surrounded by quotation marks, as there might be commas or other escape characters inside the item.

Now, when you know the data types that are in the CSV file, you can create a Java Class that can hold each record, and it's fairly easy to write a method that will create the object from a line of CSV data that is properly formatted. But, using annotations and reflection, we can design a library that can take a properly set up class and automatically create a List, containing the class we designed, filled with the data.

Let's take a look at what the class would look like, with just placeholder field names for dummy data:

@CSVHeader
public class SampleClass {
    @CSVField(index=0, type= CSVTypes.INTEGER, format="%,d")
        private int number;

    @CSVField(index=1, type= CSVTypes.BOOL)
        private boolean bool;

    @CSVField(index=2, quotes=true)
        private String string;

    @CSVField(index=3, type= CSVTypes.DATE, format="MM/dd/yyyy")
        private Date date;

    @CSVField(index=4, type= CSVTypes.DOUBLE, format="%12.4f")
        private double decimal;

    // provide default empty constructor
    public SampleClass(){}
        
    // ... other methods and such
}

And our final product can load a list with data for that class with just two lines of code:

CSVReader<SampleClass> reader = new CSVReader<>(SampleClass.class);
List<SampleClass> stuff = reader.readListFromCSV("sampledata.csv");

So here's how we do it:

Annotations

First, lets create the custom annotations. It's pretty easy, but different syntax than any other class.

Here's the layout for the annotation that will be used on the fields (minus package and import info)

@Inherited
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CSVField {
    int index();
    CSVTypes type() default CSVTypes.STRING;
    boolean quotes() default false;
    String format() default "";
}

Note that it uses several annotations itself. @inherited makes sure that inheriting class can also use this annotation. @Target specifies what level the annotation works on, constructor, method, field etc. @Retention tells the compiler when this is used, here we specify during runtime. Then we say public @interface myAnnotationName. Now we can specify any number of annotation properties. These are strange - they are somewhere in between fields and methods - they are given a data type and a name, with parentheses like a method. As you can see, a default value is allowed, which is super handy. Anything that has the default value doesn't have to be specified when you use the annotation in the class. As you can see above this is used like:

@CSVField(index=3, type=CSVTypes.DATE, format="MM/dd/yyyy")
private Date date;

This will create an annotation attached to member field date with the given properties, and the quotes property set to a default of false.

To access these properties from another class, we use Reflection. The handling class will need to have a reference to the Class that we have made. There are two main ways to do this, using MyClass.class or using the String name of the class with all package info if necessary) like Class.forName("MyClass.class")

To make our lives easier, we have our CSVReader class take this class information in two ways, first through a generic type and then by sending the .class itself. So, our signature looks like:

public class CSVReader<T> {

    private Class csvClass;
    private List<CSVInfo> fields;

    public CSVReader(Class csvClass) {
        this.csvClass = csvClass;
        fields = CSVInfo.getAnnotatedFieldInfo(csvClass);
    }

To help, we need to make another class to store the annotated field info. This can be used both be the CSVReader class and the CSVWriter. To make the resulting code cleaner, I have left the fields package-private and marked them as final, so they can be accessed without a getter but cannot be changed.

class CSVInfo {
    final int index;
    final CSVTypes type;
    final Field field;
    final boolean quotes;
    final String format;

    CSVInfo(CSVField annotation, Field field) {
        this.index = annotation.index();
        this.type = annotation.type();
        this.quotes = annotation.quotes();
        this.format = annotation.format();
        this.field = field;
    }

This class also contains a static method to get the fields from the custom class, get the annotations for each field, and fill a resulting list:

static List<CSVInfo> getAnnotatedFieldInfo(Class<?> csvClass) {
    List<CSVInfo> fields = new ArrayList<>();
    Field[] fieldArray = csvClass.getDeclaredFields();
    for (Field each : fieldArray) {
        csv.CSVField annotation = each.getAnnotation(csv.CSVField.class);
        if (annotation != null) {
            // allow private fields to be accessed/modified
            each.setAccessible(true);
            fields.add(new CSVInfo(annotation, each));
        }
    }
    return fields;
}

This is where some of the reflection happens: We send this method our class as a parameter, and then call Field[] fieldArray = csvClass.getDeclaredFields(); to get an array containing references to all of the class's fields. You can use class.getFields() if you want only the public fields. Now we loop through that array, and use getAnnotation() to return the specified annotation class for each field. If the method does not have that particular annotation, null is returned, and we can ignore that field. Otherwise, first we set the access to that field to true, then add it to the list creating a new CSVInfo object. Then we can return the list to the Reader/Writer class.

Ok, so everything is set up and what we need now is a method to take one line from the CSV file and convert it to one object. This brings us to the problem of parsing the CSV properly, which is difficult because the data can sometimes be in quotes, sometimes not, and can contain commas inside the data, so we can't just use string.split(","). I played around with Regex for a while, and then gave up and decided to write my own parsing method using Queues and a Finite State Machine, but that explanation I will leave for another tutorial. Let's start our method:

private T getObjectFromCSV(String line) {
    try {
        String[] split = CSVParser.CSVSplit(line);
        Object instance;
        try {
            instance = csvClass.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
            return null;
        }

There will be a bunch of try-catch blocks in this method, as we want to handle any exceptions thrown at this level. First, we use my parse method to return a String array of the items in the CSV line. Next we create an Object for the return type instance - at this point we need it to be Object and we can cast it to the proper class when we return it. Using the reflection method newInstance() we instantiate the object.

        for (CSVInfo each : fields) {
            if (each.index < 0 || each.index >= split.length) {
                System.out.println("Incorrect CSV entry for line:");
                System.out.println(line);
                System.out.println("Ignoring line");
                return null;
            }
            String temp = split[each.index];

Now we loop through the annotated field info we created before. First, a check to make sure the index property associated with that field exists in the CSV data we parsed, otherwise, log it and skip the line. (TODO: Use an actual Logging mechanism here.) Next, store the String representation of the data into a temp variable.

            if (!temp.isEmpty()) {
                try {
                    switch (each.type) {
                        case INTEGER:
                            int t = Integer.parseInt(temp);
                            each.field.set(instance, t);
                            break;
                        case FLOAT:
                            float f = Float.parseFloat(temp);
                            each.field.set(instance, f);
                            break;
                        case DOUBLE:
                            double d = Double.parseDouble(temp);
                            each.field.set(instance, d);
                            break;
                        case DATE:
                            SimpleDateFormat format = new SimpleDateFormat(each.format);
                            Date date = format.parse(temp);
                            each.field.set(instance, date);
                            break;
                        case BOOL:
                            boolean b = Boolean.parseBoolean(temp);
                            each.field.set(instance, b);
                            break;
                        case STRING:
                            each.field.set(instance, temp);
                            break;
                    }
                }
                catch (NumberFormatException nfe) {
                    System.out.println("Incorrect CSV entry for line: Number Format exception");
                    System.out.println(line);
                    System.out.println("Ignoring line");
                    return null;
                }
                catch (ParseException pe) {
                    System.out.println("Incorrect CSV entry for line: Problem parsing Date");
                    System.out.println(line);
                    System.out.println("Ignoring line");
                    return null;
                }
            }

First, a check to see if the temp string is empty (skip if so) and then use a switch/case expression to loop through an enum with the available data types. (This can obviously be added to here for other data types should the need arise). Here we use reflection again to actually set the value for the given field with field.set(instance, value). if we run into an issue with parsing the number or date formats, it dumps the line and logs it.

Now we can finish our method by casting the resulted object to the return type, and catch our final exception group:

        return (T) instance;
    } catch ( IllegalAccessException e) {
        e.printStackTrace();
        return null;
    }

}

You should now have a filled object, provided that nothing went wrong and the CSV data matched the class perfectly.

So what we need now is a class to loop through the entire CSV file and create a list of the objects. Let's do two methods, one which takes a local file name, and one which takes a URL to pull the info directly from a website.

public List<T> readListFromCSV(String filename) {
    List<T> results = null;
    try (BufferedReader br = new BufferedReader(new FileReader(filename))){
        results = readListFromCSV(br);
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
    return results;
}

public List<T> readListFromCSVURL(String url) {
    List<T> results = null;
    try (BufferedReader br = new BufferedReader(new InputStreamReader(new URL(url).openStream()))){
        results = readListFromCSV(br);
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
    return results;
}

Both methods create a BufferedReader and call this private method:

private List<T> readListFromCSV(BufferedReader br) throws IOException{
    List<T> results = new ArrayList<>();

    String input;
    if (csvClass.isAnnotationPresent(CSVHeader.class)) {
        CSVHeader header = (CSVHeader) csvClass.getAnnotation(CSVHeader.class);
        if (header.has_header()) {
            // ignore header line
            br.readLine();
        }
    }
    while ((input = br.readLine()) != null) {
        T t = null;
        t = getObjectFromCSV(input);
        if (t != null) {
            results.add(t);
        }
    }

    return results;
}

Note that this method can just throw exceptions further up the chain, as we have handled them in the calling method. Now we have to handle the fact that some CSV files have a 'header' line that needs to be ignored when parsing. So first we need to create another annotation:

@Inherited
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface CSVHeader {
    boolean has_header() default false;
    String header() default "";
}

This one targets the 'Type' (or Class) level, and sets a boolean if there is a header. It needs to be placed directly before the class declaration. The actual header line can be provided, used for the CSVWriter class, not the reader. This annotation is optional, if your CSV has no header you can ignore it.

That's basically it! You can create different test classes, and then create some fake data sets here.

One cool thing this allows you to do, is only pull the data you need from the full data set. Say you want only one column of data:

Using the data found here, let's just get the data from the FTE Sick Days column (column 6):

Our data object class:

@CSVHeader (has_header = true)
public class OneColumnExample {
    @CSVField(index=6, type=CSVTypes.DOUBLE, quotes=true, format="%8.4f")
    private final double daysSick;

    public OneColumnExample() {}

    public double getDaysSick() {
        return this.daysSick;
    }
}

And the test class, which loads the data, then gets the average of all items > 0:

public class OneColumnTest {
    public static void main(String[] args) {
        CSVReader<OneColumnExample> reader = new CSVReader<>(OneColumnExample.class);
        List<OneColumnExample> sickDays =
                reader.readListFromCSVURL("http://www.content.digital.nhs.uk/catalogue/PUB23358/sick-abse-rate-nhs-oct-2016-csv-textfile.csv");


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

        System.out.println(sickDays.stream()
                .mapToDouble(OneColumnExample::getDaysSick)
                .filter(x -> x > 0)
                .average());
    }
}

Note: if you test this, it is a very large (6MB) data set, takes a bit to process, but it's a great example as the CSV has a header, has every field in quotes, and contains commas inside some of those quotes.

We will leave the CSVWriter class for another day. Here's a link to the full code on gist, and again, thanks for reading, and leave comments/questions below.


r/javaexamples • • Sep 15 '16

[Request]using methods and return variables

2 Upvotes

I learned briefly on how they work. It's like if class is human Then a method can be sleep, eat, run etc. But how do you retrieve values with return method, and using parameters effeciently. I make stuff in my main method and when I try to use a method it just never seems to work


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 • • 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 • • Apr 19 '15

Getting Input from the Console : Validating and Looping

2 Upvotes

Getting Input from the Console : Validating & Looping

This seems to be one of the most asked questions in /r/javahelp and /r/learnjava - problems with getting the user input from the console.

There are two main ways to get user input from the console: The Scanner class, and the BufferedReader / InputStreamReader combo.

The Scanner Class

Scanner is usually the first method that beginner programmers learn, so I will start there, although I believe that the BufferedReader method is superior.

You first need to create an instance of a Scanner object like this:

Scanner scanner = new Scanner(System.in);

and you can read input from the console like this:

System.out.println("Enter your name:");
String name = scanner.nextLine();

Now, say you want an integer value, you can use:

int value = scanner.nextInt();

However, this is fraught with problems. For example, if the user types in a letter here it will crash your program. If you try to do a nextLine command after the nextInt call it will not properly handle the 'dangling' newline (so common an issue it's on the /r/learnjava FAQ).

Also, often times you want to be able to prompt the user multiple times, and at the same time check to see that invalid input is not entered.

So, we have to do several things here: One is to test if the user input is valid, according to the program's need. Second is to make the user keep entering the input until it is valid. Third would be to allow for looping the input for an indefinite amount of times, until some sort of closing condition (called a sentinel) is satisfied.

Validating Input

Using the Try - Catch method

import java.util.Scanner;
import java.util.InputMismatchException;

public class Input
{
	public static void main( String [] args )
	{
		Scanner scanner = new Scanner(System.in);
		int value = 0;
		try
		{
			System.out.print("Enter an integer:");
			value = scanner.nextInt();
		}
		catch (InputMismatchException ime)
		{
			System.err.println("Incorrect entry.");
		}
		System.out.println("Your entry is:" + value);

	}

}

This uses Java's Exception handling capabilities to avoid the program crashing when incorrect entries are input. Compile the above code, and enter "qwert" or any random mashing of the keys and see what happens. The program still runs, but the variable value stays at 0.

Now, this is fairly useless, as we need to prompt the user again for a correct entry. we will use a while loop for this.

import java.util.Scanner;
import java.util.InputMismatchException;

public class Input
{
	public static void main( String [] args )
	{
		Scanner scanner = new Scanner(System.in);
		
		// set value initially to a number outside the range we want
		int value = -1;
		
		// loop, while the value is below zero
		while( value < 0)
		{
			try
			{
				System.out.print("Enter a positive integer:");
				value = scanner.nextInt();
			}
			// if the user types in anything but an integer, 
			// it will 'throw' this 'exception'.
			catch (InputMismatchException ime)
			{
				System.err.println("Incorrect entry.");
				
				// clear the keyboard buffer
				scanner.nextLine();
			}
		}

		System.out.println("Your entry is:" + value);

	}

}

This will make the user keep entering values until a valid entry is made.

Now let's take this code, make it into a static method, and then use another while loop to have the user be able to enter multiple things.

Here the user enters integers until he is done, ending it by typing in a sentinel value, or a value that we decide ahead of time will be the code to stop.

import java.util.Scanner;
import java.util.InputMismatchException;

public class Input
{
	public static Scanner scanner = new Scanner(System.in);
	public static final int SENTINEL = 9999;

	// static method to get the input and validate
	public static int getIntegerInput(String prompt)
	{
		int value = -1;
		while (value < 0)
		{
			try
			{
				System.out.print(prompt);
				value = scanner.nextInt();
			}
			catch (InputMismatchException ime)
			{
				System.err.println("Incorrect entry. Please input only a positive integer.");
				scanner.nextLine();
			}
		}
		return value;
	}
	public static void main( String [] args )
	{
		int value = 0;
		int sum = 0;
		int count = 1;

		// loop until user enters sentinel value
		while (value != SENTINEL)
		{
			value = getIntegerInput("Please enter a positive integer (or 9999 to quit) " + count + ":");

			// don't add sentinel value to sum or count
			if (value != SENTINEL)
			{
				sum += value;
				count++;
			}
		}
		System.out.println("The sum of your entered numbers is: " + sum);
		System.out.println("The average of your entered value is: " + (float)sum/(float)count);
	}

}

here is another way to get only an integer, using REGEX:

public static int getIntegerFromScanner(String prompt)
{
	Scanner intScanner = new Scanner(System.in);
	int n = -1;
	while (n < 0)
	{
		try
		{
			System.out.print(prompt);
			
			// use REGEX pattern to allow only digits
			while (!intScanner.hasNext("\\d+"))
			{
				System.out.print("\n" + prompt);
				intScanner.next();
			}
			n = intScanner.nextInt();
		}
		catch ( InputMismatchException ime)
		{
			System.out.println("Incorrect input, please type an integer.");
			intScanner.next();
		}
	}
	return n;
}

Here is a way to get only two possible string values from the user, like a yes or no, using a boolean value that is only turned to true if the proper conditions are met:

	boolean isValid = false;
	String input = "";
	while (!isValid)
	{
		System.out.print("Enter 'y' or 'n':");
		input = scanner.nextLine();
		if (input.equalsIgnoreCase("y") || input.equalsIgnoreCase("n"))
		{
			isValid = true;
		}
		else
		{
			System.out.println("Invalid entry.");
		}
	}

Here is a more complicated example, using the other input method I discussed above, which uses a separate boolean method to validate. This program lets the user add integers one at a time, in a range specified in the code, until they type 'stop',then it adds them to a linked list, then sorts and displays them.

import java.util.*;
import java.io.*;

public class Validate
{

	public static String getInputLine(String prompt)
	{

		String inString = "";
		try
		{
			// create buffered reader instance
			BufferedReader ibr = new BufferedReader( new InputStreamReader(System.in));
			while (inString.equals(""))
			{
				System.out.print(prompt);
				inString = ibr.readLine();
			}

		}

		catch (IOException ioe)
		{
			ioe.printStackTrace();
		}
		return inString;
	}



	public static boolean isValid(String input, int min, int max, String stop)
	{
		boolean valid;
		if (input.equalsIgnoreCase(stop))
		{
			valid = true;
		}
		else
		{
			int n;
			try
			{
				n = Integer.parseInt(input);
				if (n >= min && n <=max)
				{
					valid = true;
				}
				else
				{
					valid = false;
				}
			}
			catch (NumberFormatException nfe)
			{
				valid = false;
			}
		}
		System.out.println(valid);
		if (!valid)
		{
			System.out.println("Incorrect entry. Must be an integer between " + (min - 1) + " and " + (max + 1));
		}
		return valid;
	}



	public static void main( String [] args )
	{
		LinkedList<Integer> list = new LinkedList<>();
		String inline = "";
		do
		{
			do
			{
				inline = getInputLine("Enter a number between 1 and 100, inclusive (or 'stop' when done)>>");
				if (inline.equalsIgnoreCase("quit"))
				{
					System.exit(0);
				}
			}
			while (!isValid(inline, 1, 100, "stop"));

			if (!inline.equals("stop"))
			{
				list.add(Integer.parseInt(inline));
			}

		} while (!inline.equals("stop"));



		if (list.peek()!= null)
		{
			System.out.println("Max:" + Collections.max(list));
			Iterator i = list.iterator();

			while (i.hasNext())
			{
				System.out.println(i.next());
			}
			Collections.sort(list);
			System.out.println("====================");

			for (Integer current : list)
			{
				System.out.println(current);
			}
		}





	}

}

r/javaexamples • • Apr 18 '15

Using Comparator to sort a list of objects

2 Upvotes

Using Comparator to sort a list of objects

Using Java's sort function is very easy when you have an array or list of simple data types like integer or double, but what happens when you have a more complex object and you want to be able to sort by different fields?

This is where java.util.Comparator comes in. We will also be using a technique called Anonymous Inner Classes to implement our different Comparators.

We have a simple class, Employee

 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;
	 }

We want to make functions to sort by each of the member variables.

For the first one, id, we make a Comparator 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());
		 }
	 };

An anonymous class allows you to declare and instantiate the class at the same time. Here we are declaring a Comparator named SortByEmployeeID that is given as parameters two Employee Objects, and returns a String compareTo on the values from the getID() method. This is then used by the Collections.sort() function you will see later.

We can make a comparator for the next string field in exactly the same way.

When we get to the integer field, we do it slightly differently:

	// Make anonymous inner class to sort by member variable 'salary' - integer instead of string
	public static Comparator<Employee> SortBySalary = new Comparator<Employee>()
	{
		public int compare(Employee employee1, Employee employee2)
		{
			return employee1.getSalary() - employee2.getSalary();
		}
	};

Here we just subtract the second integer value from the first. This will give us an ascending sort. for a descending sort, we just reverse that:

	// Make anonymous inner class to sort by member variable 'salary' - Descending
	public static Comparator<Employee> SortBySalaryDescending = new Comparator<Employee>()
	{
		public int compare(Employee employee1, Employee employee2)
		{
			// simply reverse for descending
			return employee2.getSalary() - employee1.getSalary();
		}
	};

To use these the syntax is simple:

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

So, lets put it all together:

 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.Comparator;
 import java.lang.Object;

 public class ObjectComparator
 {
	 // 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;
		 }

		 // 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());
			 }
		 };

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

		// Make anonymous inner class to sort by member variable 'salary' - integer instead of string
		public static Comparator<Employee> SortBySalary = new Comparator<Employee>()
		{
			public int compare(Employee employee1, Employee employee2)
			{
				return employee1.getSalary() - employee2.getSalary();
			}
		};

		// Make anonymous inner class to sort by member variable 'salary' - Descending
		public static Comparator<Employee> SortBySalaryDescending = new Comparator<Employee>()
		{
			public int compare(Employee employee1, Employee employee2)
			{
				// simply reverse for descending
				return employee2.getSalary() - employee1.getSalary();
			}
		};

		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
		ArrayList<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 ==========================");
		for (Employee current : employeeList)
		{
			System.out.println(current);
		}

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

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

		for (Employee current : employeeList)
		{
			System.out.println(current);
		}

		// sort by name
		Collections.sort(employeeList, Employee.SortByEmployeeName);

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

		for (Employee current : employeeList)
		{
			System.out.println(current);
		}

		// sort by salary
		Collections.sort(employeeList, Employee.SortBySalary);

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

		for (Employee current : employeeList)
		{
			System.out.println(current);
		}

		// sort by salary - descending
		Collections.sort(employeeList, Employee.SortBySalaryDescending);

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

		for (Employee current : employeeList)
		{
			System.out.println(current);
		}


	}
}

And here is the output:

Unsorted ==========================
Employee ID:7123r
Name:Dole, Bob
Salary: 42000

Employee ID:1234d
Name:Johnson, John
Salary: 150000

Employee ID:2345x
Name:Billson, Bill
Salary: 35000

Employee ID:0019b
Name:Dickerson, Dick
Salary: 10000

Sorted by ID =========================
Employee ID:0019b
Name:Dickerson, Dick
Salary: 10000

Employee ID:1234d
Name:Johnson, John
Salary: 150000

Employee ID:2345x
Name:Billson, Bill
Salary: 35000

Employee ID:7123r
Name:Dole, Bob
Salary: 42000

Sorted by NAME =========================
Employee ID:2345x
Name:Billson, Bill
Salary: 35000

Employee ID:0019b
Name:Dickerson, Dick
Salary: 10000

Employee ID:7123r
Name:Dole, Bob
Salary: 42000

Employee ID:1234d
Name:Johnson, John
Salary: 150000

Sorted by SALARY =========================
Employee ID:0019b
Name:Dickerson, Dick
Salary: 10000

Employee ID:2345x
Name:Billson, Bill
Salary: 35000

Employee ID:7123r
Name:Dole, Bob
Salary: 42000

Employee ID:1234d
Name:Johnson, John
Salary: 150000

Sorted by SALARY DESCENDING=========================
Employee ID:1234d
Name:Johnson, John
Salary: 150000

Employee ID:7123r
Name:Dole, Bob
Salary: 42000

Employee ID:2345x
Name:Billson, Bill
Salary: 35000

Employee ID:0019b
Name:Dickerson, Dick
Salary: 10000

r/javaexamples • • 2d ago

Threadline: a step-through visualizer for the GIL, threading, and asyncio

Thumbnail reddit.com
1 Upvotes

r/javaexamples • • Jul 27 '26

Looking for Java Mentors 🚀

Thumbnail reddit.com
1 Upvotes