How do I iterate through date range in Java?

The following code snippet shows you how to iterate through a range of dates in Java. We use the Java Date Time API. We do increment and decrement iteration using a simple for loop.

Here are the steps:

  • We declare the start and end date of the loop, the dates are instance of java.time.LocalDate.
  • Create a for loop.
  • In the for loop we set the initialization variable the start date.
  • The loop executed if the date is less than end date, using the isBefore() method, otherwise it will be terminated.
  • The date will be incremented by 1 on each loop.
package org.kodejava.datetime;

import java.time.LocalDate;
import java.time.format.TextStyle;
import java.util.Locale;

public class DateIteration {
    public static void main(String[] args) {
        LocalDate start = LocalDate.of(2023, 10, 1);
        LocalDate end = LocalDate.of(2023, 10, 8);

        System.out.println("Start = " + start);
        System.out.println("End   = " + end);
        System.out.println("--------------------");

        for (LocalDate date = start; date.isBefore(end); date = date.plusDays(1)) {
            System.out.printf("Date %tD is %s%n", date, date.getDayOfWeek());
        }

        System.out.println("--------------------");

        for (LocalDate date = end; date.isAfter(start); date = date.minusDays(1)) {
            System.out.printf("Date %tD is %s%n", date, date.getDayOfWeek()
                    .getDisplayName(TextStyle.SHORT, Locale.getDefault()));
        }
    }
}

Running the code snippet gives you the following output:

Start = 2023-10-01
End   = 2023-10-08
--------------------
Date 10/01/23 is SUNDAY
Date 10/02/23 is MONDAY
Date 10/03/23 is TUESDAY
Date 10/04/23 is WEDNESDAY
Date 10/05/23 is THURSDAY
Date 10/06/23 is FRIDAY
Date 10/07/23 is SATURDAY
--------------------
Date 10/08/23 is Sun
Date 10/07/23 is Sat
Date 10/06/23 is Fri
Date 10/05/23 is Thu
Date 10/04/23 is Wed
Date 10/03/23 is Tue
Date 10/02/23 is Mon

Next, we are going to use while loop.

  • Define the start and end date to loop
  • We increment the start date by 1 day.
  • Execute the loop if the start date is before end date.
package org.kodejava.datetime;

import java.time.LocalDate;

public class WhileDateIteration {
    public static void main(String[] args) {
        LocalDate start = LocalDate.of(2023, 10, 1).minusDays(1);
        LocalDate end = LocalDate.of(2023, 10, 8);

        while ((start = start.plusDays(1)).isBefore(end)) {
            System.out.printf("Date %tD is %s%n", start, start.getDayOfWeek());
        }
    }
}

The result of the code snippet above is:

Date 10/01/23 is SUNDAY
Date 10/02/23 is MONDAY
Date 10/03/23 is TUESDAY
Date 10/04/23 is WEDNESDAY
Date 10/05/23 is THURSDAY
Date 10/06/23 is FRIDAY
Date 10/07/23 is SATURDAY

To use the Java stream, we can do it like the following code snippet:

package org.kodejava.datetime;

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.stream.Stream;

public class StreamDateIteration {
    public static void main(String[] args) {
        LocalDate start = LocalDate.of(2023, 10, 1);
        LocalDate end = LocalDate.of(2023, 10, 8);

        Stream.iterate(start, date -> date.plusDays(1))
                .limit(ChronoUnit.DAYS.between(start, end))
                .forEach(date -> {
                    System.out.printf("Date %tD is %s%n", date, date.getDayOfWeek());
                });
    }
}

The result of the code snippet above is:

Date 10/01/23 is SUNDAY
Date 10/02/23 is MONDAY
Date 10/03/23 is TUESDAY
Date 10/04/23 is WEDNESDAY
Date 10/05/23 is THURSDAY
Date 10/06/23 is FRIDAY
Date 10/07/23 is SATURDAY

From Java 9 we can use LocalDate.datesUntil() method. It will iterate from the date to the specified end date by increment step of 1 day or the specified increment of Period.

package org.kodejava.datetime;

import java.time.LocalDate;
import java.time.Period;

public class DatesUntilDateIteration {
    public static void main(String[] args) {
        LocalDate start = LocalDate.of(2023, 10, 1);
        LocalDate end = LocalDate.of(2023, 10, 8);

        start.datesUntil(end).forEach(date -> {
            System.out.printf("Date %tD is %s%n", date, date.getDayOfWeek());
        });

        start.datesUntil(end, Period.ofDays(2)).forEach(System.out::println);
    }
}

Running the code snippet produces the following result:

Date 10/01/23 is SUNDAY
Date 10/02/23 is MONDAY
Date 10/03/23 is TUESDAY
Date 10/04/23 is WEDNESDAY
Date 10/05/23 is THURSDAY
Date 10/06/23 is FRIDAY
Date 10/07/23 is SATURDAY
2023-10-01
2023-10-03
2023-10-05
2023-10-07

How do I create a string of repeated characters?

The following code demonstrates how to create a string of repeated characters. We use the String.repeat(int count) method introduced in Java 11. This method takes one parameter of type int which is the number of times to repeat the string. The count must be a positive number, a negative number will cause this method to throw java.lang.IllegalArgumentException.

In the snippet below, we use the method to repeat characters and draw some triangles. We combine the repeat() method with a for loop to draw the triangles.

package org.kodejava.basic;

public class StringRepeatDemo {
    public static void main(String[] args) {
        String star = "*";
        String fiveStars = star.repeat(5);
        System.out.println("fiveStars = " + fiveStars);

        String arrow = "-->";
        String arrows = arrow.repeat(10);
        System.out.println("arrows    = " + arrows);
    }
}

The outputs of the code snippet above are:

fiveStars = *****
arrows    = -->-->-->-->-->-->-->-->-->-->
package org.kodejava.basic;

public class StringRepeatDemo {
    public static void main(String[] args) {
        String asterisk = "#";
        for (int i = 1; i <= 10; i++) {
            System.out.println(asterisk.repeat(i));
        }
}

The outputs of the code snippet above are:

#
##
###
####
#####
######
#######
########
#########
##########
package org.kodejava.basic;

public class StringRepeatDemo {
    public static void main(String[] args) {
        int height = 10;
        for (int i = 1, j = 1; i <= height; i++, j += 2) {
            System.out.println(" ".repeat(height - i) + "*".repeat(j));
        }
    }
}

The outputs of the code snippet above are:

         *
        ***
       *****
      *******
     *********
    ***********
   *************
  ***************
 *****************
*******************

How do I convert datetime string with optional part to a date object?

Since JDK 8, we can create a datetime formatter / parser pattern that can have optional sections. When parsing a datetime string that contains optional values, for example, a date without time part or a datetime without second part, we can create a parsing pattern wrapped within the [] symbols. The [ character is the optional section start symbol, and the ] character is the optional section end symbol. The pattern inside this symbol will be considered as an optional value.

We can use the java.time.format.DateTimeFormatter class to parse the string of datetime or format the datetime object, and use it with the new Java time API classes such as java.time.LocalDate or java.time.LocalDateTime to convert the string into respective LocalDate or LocalDateTime object as show in the code snippet below.

package org.kodejava.datetime;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class DateTimeParseOptionalParts {
    public static final String OPT_TIME_PATTERN = "yyyy-MM-dd[ HH:mm[:ss]]";
    public static final String OPT_SECOND_PATTERN = "yyyy-MM-dd HH:mm[:ss]";

    public static void main(String[] args) {
        DateTimeFormatter optTimeFormatter = DateTimeFormatter.ofPattern(OPT_TIME_PATTERN);
        LocalDate date1 = LocalDate.parse("2023-08-28", optTimeFormatter);
        LocalDate date2 = LocalDate.parse("2023-08-28 17:15", optTimeFormatter);
        LocalDate date3 = LocalDate.parse("2023-08-28 17:15:30", optTimeFormatter);
        System.out.println("date1 = " + date1);
        System.out.println("date2 = " + date2);
        System.out.println("date3 = " + date3);

        DateTimeFormatter optSecondFormatter = DateTimeFormatter.ofPattern(OPT_SECOND_PATTERN);
        LocalDateTime datetime1 = LocalDateTime.parse("2023-08-28 17:15", optSecondFormatter);
        LocalDateTime datetime2 = LocalDateTime.parse("2023-08-28 17:15:30", optSecondFormatter);
        System.out.println("datetime1 = " + datetime1);
        System.out.println("datetime2 = " + datetime2);
    }
}

Here are the outputs of the code snippet above:

date1 = 2023-08-28
date2 = 2023-08-28
date3 = 2023-08-28
datetime1 = 2023-08-28T17:15
datetime2 = 2023-08-28T17:15:30

How do I get the number of processors available to the JVM?

The Runtime.getRuntime().availableProcessors() method returns the maximum number of processors available to the Java virtual machine, the value will never be smaller than one. Knowing the number of available processor you can use it for example to limit the number of thread in your application when you are writing a multi-thread code.

package org.kodejava.lang;

public class NumberProcessorExample {
    public static void main(String[] args) {
        final int processors = Runtime.getRuntime().availableProcessors();
        System.out.println("Number of processors = " + processors);
    }
}

Running the code snippet give you something like:

Number of processors = 8

How do I calculate days between two dates excluding weekends and holidays?

The code snippet below shows you a simple way to calculate days between two dates excluding weekends and holidays. As an example, you can use this function for calculating work days. The snippet utilize the java.time API and the Stream API to calculate the value.

What we do in the code below can be described as the following:

  • Create a list of holidays. The dates might be read from a database or a file.
  • Define filter Predicate for holidays.
  • Define filter Predicate for weekends.
  • These predicates will be use for filtering the days between two dates.
  • Define the startDate and the endDate to be calculated.
  • Using Stream.iterate() we iterate the dates, filter it based on the defined predicates.
  • Finally, we get the result as list.
  • The actual days between is the size of the list, workDays.size().
package org.kodejava.datetime;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.Month;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Stream;

public class DaysBetweenDates {
    public static void main(String[] args) {
        List<LocalDate> holidays = new ArrayList<>();
        holidays.add(LocalDate.of(2022, Month.DECEMBER, 26));
        holidays.add(LocalDate.of(2023, Month.JANUARY, 2));

        Predicate<LocalDate> isHoliday = holidays::contains;
        Predicate<LocalDate> isWeekend = date -> date.getDayOfWeek() == DayOfWeek.SATURDAY
                || date.getDayOfWeek() == DayOfWeek.SUNDAY;

        LocalDate startDate = LocalDate.of(2022, Month.DECEMBER, 23);
        LocalDate endDate = LocalDate.of(2023, Month.JANUARY, 3);
        System.out.println("Start date = " + startDate);
        System.out.println("End date   = " + endDate);

        // Days between startDate inclusive and endDate exclusive
        long daysBetween = ChronoUnit.DAYS.between(startDate, endDate);
        System.out.println("Days between = " + daysBetween);

        List<LocalDate> workDays = Stream.iterate(startDate, date -> date.plusDays(1))
                .limit(daysBetween)
                .filter(isHoliday.or(isWeekend).negate())
                .toList();

        long actualDaysBetween = workDays.size();
        System.out.println("Actual days between = " + actualDaysBetween);
    }
}

Running the code snippet above give us the following result:

Start date = 2022-12-23
End date   = 2023-01-03
Days between = 11
Actual days between = 5

How do I discover the quarter of a given date?

The following code snippet shows you a various way to get the quarter of a given date. Some methods that we use below are:

  • Using the new java.time API of Java 8 IsoFields.QUARTER_OF_YEAR.
  • Using Java 8 DateTimeFormatter pattern of Q or q. The length of “q” give us a different result.
  • Using java.util.Date.
  • Using java.util.Calendar.
  • Get the quarter from an array of string.

Let’s see the code snippet in action.

package org.kodejava.datetime;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.IsoFields;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

public class DateQuarter {
    public static void main(String[] args) {
        // Using Java 8
        LocalDate now = LocalDate.now();
        int quarter = now.get(IsoFields.QUARTER_OF_YEAR);
        System.out.println("quarter  = " + quarter);

        // Using DateTimeFormatter Q / q, set the Locale to get value
        // in local format
        String quarter1 = LocalDate.of(2023, 8, 17)
                .format(DateTimeFormatter.ofPattern("q", Locale.US));
        String quarter2 = LocalDate.of(2023, 8, 17)
                .format(DateTimeFormatter.ofPattern("qq", Locale.US));
        String quarter3 = LocalDate.of(2023, 8, 17)
                .format(DateTimeFormatter.ofPattern("qqq", Locale.US));
        String quarter4 = LocalDate.of(2023, 8, 17)
                .format(DateTimeFormatter.ofPattern("qqqq", Locale.US));
        System.out.println("quarter1 = " + quarter1);
        System.out.println("quarter2 = " + quarter2);
        System.out.println("quarter3 = " + quarter3);
        System.out.println("quarter4 = " + quarter4);

        // Using older version of Java
        Date today = new Date();
        quarter = (today.getMonth() / 3) + 1;
        System.out.println("quarter = " + quarter);

        // Using java.util.Calendar object. For certain date
        // we can set the calendar date using setTime() method.
        Calendar calendar = Calendar.getInstance();
        quarter = (calendar.get(Calendar.MONTH) / 3) + 1;
        System.out.println("quarter = " + quarter);

        // Custom the quarter as text
        String[] quarters = new String[]{"Q1", "Q2", "Q3", "Q4"};
        String quarterString = quarters[quarter - 1];
        System.out.println("quarterString = " + quarterString);
    }
}

And here are the result of the code snippet above:

quarter  = 1
quarter1 = 3
quarter2 = 03
quarter3 = Q3
quarter4 = 3rd quarter
quarter = 1
quarter = 1
quarterString = Q1

How do I export MySQL database schema into markdown format?

The following code example demonstrate how to export MySQL database schema into markdown table format. We get the table structure information by executing MySQL’s DESCRIBE statement.

The steps we do in the code snippet below:

  • Connect to the database.
  • We obtain the list of table name from the database / schema.
  • Executes DESCRIBE statement for each table name.
  • Read table structure information such as field, type, null, key, default and extra.
  • Write the information into markdown table format and save it into table.md.

And here are the complete code snippet.

package org.kodejava.jdbc;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class DescribeMySQLToMarkDown {
    private static final String URL = "jdbc:mysql://localhost/kodejava";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "";

    public static void main(String[] args) {
        String tableQuery = """
                select table_name
                from information_schema.tables
                where table_schema = 'kodejava'
                  and table_type = 'BASE TABLE'
                order by table_name;
                """;

        try (Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD)) {
            Statement stmt = connection.createStatement();
            ResultSet resultSet = stmt.executeQuery(tableQuery);
            List<String> tables = new ArrayList<>();
            while (resultSet.next()) {
                tables.add(resultSet.getString("table_name"));
            }

            System.out.println(tables.size() + " tables found.");

            try (BufferedWriter writer = new BufferedWriter(new FileWriter("table.md"))) {
                for (String table : tables) {
                    System.out.println("Processing table: " + table);
                    Statement statement = connection.createStatement();
                    ResultSet descResult = statement.executeQuery("DESCRIBE " + table);

                    writer.write(String.format("Table Name: **%s**%n%n", table));
                    writer.write("| Field Name | Data Type | Null | Key | Default | Extra |\n");
                    writer.write("|:---|:---|:---|:---|:---|:---|\n");
                    while (descResult.next()) {
                        String field = descResult.getString("field");
                        String type = descResult.getString("type");
                        String nullInfo = descResult.getString("null");
                        String key = descResult.getString("key");
                        String defaultInfo = descResult.getString("default");
                        String extra = descResult.getString("extra");
                        String line = String.format("| %s | %s | %s | %s | %s | %s |%n",
                                field, type, nullInfo, key, defaultInfo, extra);
                        writer.write(line);
                    }
                    writer.write("\n<br/>\n<br/>\n");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

This code snippet will produce something like below. I have tidy up the markdown for a better presentation.

Table Name: **books**

| Field Name | Data Type       | Null | Key | Default | Extra          |
|:-----------|:----------------|:-----|:----|:--------|:---------------|
| id         | bigint unsigned | NO   | PRI | null    | auto_increment |
| isbn       | varchar(30)     | NO   |     | null    |                |

<br/>
<br/>

Maven dependencies

<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <version>8.1.0</version>
</dependency>

Maven Central

How do I find Java version?

The simplest way to get the Java version is by running the java -version command in your terminal application or Windows command prompt. If Java is installed and available on your path you can get information like below.

java -version                                     
java version "17" 2021-09-14 LTS
Java(TM) SE Runtime Environment (build 17+35-LTS-2724)                       
Java HotSpot(TM) 64-Bit Server VM (build 17+35-LTS-2724, mixed mode, sharing)

Using System Properties

But if you want to get Java version from your Java class or application you can obtain the Java version by calling the System.getProperty() method and provide the property key as argument. Here are some property keys that related to Java version that you can read from the system properties.

package org.kodejava.lang;

public class JavaVersion {
    public static void main(String[] args) {
        String version = System.getProperty("java.version");
        String versionDate = System.getProperty("java.version.date");
        String runtimeVersion = System.getProperty("java.runtime.version");
        String vmVersion = System.getProperty("java.vm.version");
        String classVersion = System.getProperty("java.class.version");
        String specificationVersion = System.getProperty("java.specification.version");
        String vmSpecificationVersion = System.getProperty("java.vm.specification.version");

        System.out.println("java.version: " + version);
        System.out.println("java.version.date: " + versionDate);
        System.out.println("java.runtime.version: " + runtimeVersion);
        System.out.println("java.vm.version: " + vmVersion);
        System.out.println("java.class.version: " + classVersion);
        System.out.println("java.specification.version: " + specificationVersion);
        System.out.println("java.vm.specification.version: " + vmSpecificationVersion);
    }
}

Running the code above give you output like the following:

java.version: 17
java.version.date: 2021-09-14
java.runtime.version: 17+35-LTS-2724
java.vm.version: 17+35-LTS-2724
java.class.version: 61.0
java.specification.version: 17
java.vm.specification.version: 17

Using Runtime.version()

Since JDK 9 we can use Runtime.version() to get Java runtime version. The feature(), interim(), update and patch() methods of the Runtime.Version class are added in JDK 10. These methods is a replacement for the major(), minor() and security() methods of JDK 9.

Below is the code snippet that demonstrate the Runtime.version().

package org.kodejava.lang;

public class RuntimeVersion {
    public static void main(String[] args) {
        System.out.println("Version: " + Runtime.version());
        System.out.println("Feature: " + Runtime.version().feature());
        System.out.println("Interim: " + Runtime.version().interim());
        System.out.println("Update: " + Runtime.version().update());
        System.out.println("Patch: " + Runtime.version().patch());
        System.out.println("Pre: " + Runtime.version().pre().orElse(""));
        System.out.println("Build: " + Runtime.version().build().orElse(null));
        System.out.println("Optional: " + Runtime.version().optional().orElse(""));
    }
}

Running the code snippet above produce the following output:

Version: 17+35-LTS-2724
Feature: 17
Interim: 0
Update: 0
Patch: 0
Pre: 
Build: 35
Optional: LTS-2724

Here are the summary of outputs running the above code using some JDKs installed on my machine.

Version Feature Interim Update Patch Pre Build Optional
10.0.2+13 10 0 2 0 13
11.0.6+8-LTS 11 0 6 0 8 LTS
12.0.2+10 12 0 2 0 10
13.0.2+8 13 0 2 0 8
14+36-1461 14 0 0 0 36 1461
15.0.2+7-27 15 0 2 0 7 27
17+35-LTS-2724 17 0 0 0 35 LTS-2724

Filtering JList Component Models

Filter items in a long list are often accomplished using the JTextField component. As the user inputs into the JTextField component, the set of items shown in the list is narrowed to just those things that correspond to the input received from the user.

It is necessary to utilize two elements to implement this function of the JList component, one of which is a model that filters a set of elements based on some text. The other executes the filter method when the user enters text.

Implementing the input field is a simpler job, so let’s start with it in our review of the implementation process. The JTextField component model is a document used with a Swing set of components. It is necessary to implement the DocumentListener interface in the model in order to monitor input to a Document. Text input, updating, and deletion are tracked using three methods defined below:

  • public void insertUpdate (DocumentEvent event)
  • public void changedUpdate (DocumentEvent event)
  • public void removeUpdate (DocumentEvent event)

When the model attributes are updated, the changedUpdate() method is used to update the model. It is possible that it will not be realized. In order to avoid duplicating filtering actions across all three methods, the generic method generated in the custom model is simply called by the other two. A detailed explanation of the JTextField component, which is used for filtering in the JList component, may be found in the following section:

JTextField input = new JTextField(); 
String lastSearch = ""; 

DocumentListener listener = new DocumentListener() { 
    public void insertUpdate(DocumentEvent event) { 
        Document doc = event.getDocument(); 
        lastSearch = doc.getText(0, doc.getLength()); 
        ((FilteringModel)getModel()).filter(lastSearch); 
    } 

    public void removeUpdate(DocumentEvent event) { 
        Document doc = event.getDocument(); 
        lastSearch = doc.getText(0, doc.getLength()); 
        ((FilteringModel)getModel()).filter(lastSearch); 
    }

    public void changedUpdate(DocumentEvent event) {
    } 
}; 

input.getDocument().addDocumentListener(listener);

In order to avoid being restricted to just using the JTextField component that was generated using the JList, the installJTextField() method is used, which attaches the event listener to the component that was built using the JList in the first place. In addition, a mechanism is provided to eliminate this match. Through the usage of these methods, the user of a filtering JList may choose to use their own JTextField in place of the default one.

public void installJTextField(JTextField input) { 
    input.getDocument().addDocumentListener(listener); 
} 

public void unnstallJTextField(JTextField input) { 
    input.getDocument().removeDocumentListener(listener); 
}

After that, the filtering model is taken into consideration. This case implements the filter() function, which is invoked by methods that implement the DocumentListener interface, as seen below. To put this strategy into action, you’ll need to have two lists of objects on hand: a source list and a filtered list of items. Because you are inheriting from the AbstractListModel class, you must implement some of the methods listed below in your code:

  • Constructor
  • Method for adding items to the model is being implemented in this project.
  • getElementAt() is used to get an element.
  • getSize() is used to retrieve sizes.
  • The constructor produces two instances of the List objects. The type of objects that are stored as List elements does not matter. Therefore List objects are generated to carry items of the following types:
List<Object> list; 
List<Object> filteredList; 

public FilteringModel() { 
    list = new ArrayList<>(); 
    filteredList = new ArrayList<>(); 
}

Model elements are added by adding them to the original model and then filtering the resulting model with the previously added elements. Optimization of this approach may be achieved by using a method to filter a single element when it is added; however, in this implementation, the filter() function is invoked when an element is added, which is also used to filter the whole list. (It should be noted that the event implementation in the DocumentListener also invokes the filter() method.) As a result, even when only one item is added to the list, the whole list is filtered, with each item that matches the search parameters being added to the filtered list.

public void addElement(Object element) { 
    list.add(element); 
    filter(); 
}

The size of the returned model is the same as the size of the filtered list, but not the same as the original:

public int getSize() { 
    return filteredList.size(); 
}

Similar to the technique for obtaining the size of a model, the method for obtaining an item from a list returns elements from the filtered list rather than the original list. In order to avoid having to go through the complete list, it has been implemented as follows:

public Object getElementAt(int index) { 
    Object returnValue; 
    if (index < filteredList.size()) { 
        returnValue = filteredList.get(index); 
    } else { 
        returnValue = null;
    } 
    return returnValue; 
}

Finally, the filter() method is responsible for most of the work. Because you have no way of knowing whether the new search string will broaden or limit the set of items, the quickest and most straightforward solution is to remove the whole filtered list and replace it with items that fit your search criteria from the original list. A match may be discovered at the beginning of a line as well as at any point throughout it. An example of searching for the letter “A” is shown below. This function enables you to locate items in a string that begin with the capital letter “A” or contain the letter “A” at any point in the string.

void filter(String search) {
    filteredList.clear();
    for (Object element: list) {
        if (element.toString().contains(search)) {
            filteredList.add(element); 
        } 
    } 
    fireContentsChanged(this, 0, getSize()); 
}

It is important to note that the search in this approach is case-sensitive. You may alter the method to implement a case-insensitive search and start the search at the beginning of the string.

After you have added entries to the filtered list, you may also sort the results. This operation requires your familiarity with the model’s contents. The function toString() is currently used by search, which does not indicate that it may include elements of a suitable type that can also be sorted when it is performed.

Here is a full implementation of the JList filter element with an inner class ListModel, as seen in the accompanying code sample. This class implements the DocumentListener interface, which the text component uses to listen for new documents. Although the addition of this class may seem needless at first look, given that filtering is only done for this model, the specification of behavior in this implementation is the most accurate.

package org.kodejava.swing;

import javax.swing.AbstractListModel;
import javax.swing.JList;
import javax.swing.JTextField;
import javax.swing.ListModel;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import java.util.ArrayList;
import java.util.List;

public class FilteringJList extends JList<Object> {
    private JTextField input;

    public FilteringJList() {
        setModel(new FilteringModel());
    }

    public void installJTextField(JTextField input) {
        if (input != null) {
            this.input = input;
            FilteringModel model = (FilteringModel) getModel();
            input.getDocument().addDocumentListener(model);
        }
    }

    public void uninstallJTextField(JTextField input) {
        if (input != null) {
            FilteringModel model = (FilteringModel) getModel();
            input.getDocument().removeDocumentListener(model);
            this.input = null;
        }
    }

    public void setModel(ListModel<Object> model) {
        if (!(model instanceof FilteringModel)) {
            throw new IllegalArgumentException();
        } else {
            super.setModel(model);
        }
    }

    public void addElement(Object element) {
        ((FilteringModel) getModel()).addElement(element);
    }

    private static class FilteringModel extends AbstractListModel<Object> implements DocumentListener {
        List<Object> list;
        List<Object> filteredList;
        String lastFilter = "";

        public FilteringModel() {
            list = new ArrayList<>();
            filteredList = new ArrayList<>();
        }

        public void addElement(Object element) {
            list.add(element);
            filter(lastFilter);
        }

        public int getSize() {
            return filteredList.size();
        }

        public Object getElementAt(int index) {
            Object returnValue;
            if (index < filteredList.size()) {
                returnValue = filteredList.get(index);
            } else {
                returnValue = null;
            }
            return returnValue;
        }

        void filter(String search) {
            filteredList.clear();
            for (Object element : list) {
                if (element.toString().contains(search)) {
                    filteredList.add(element);
                }
            }
            fireContentsChanged(this, 0, getSize());
        }

        public void insertUpdate(DocumentEvent event) {
            Document doc = event.getDocument();
            try {
                lastFilter = doc.getText(0, doc.getLength());
                filter(lastFilter);
            } catch (BadLocationException ble) {
                System.err.println("Bad location: " + ble);
            }
        }

        public void removeUpdate(DocumentEvent event) {
            Document doc = event.getDocument();
            try {
                lastFilter = doc.getText(0, doc.getLength());
                filter(lastFilter);
            } catch (BadLocationException ble) {
                System.err.println("Bad location: " + ble);
            }
        }

        public void changedUpdate(DocumentEvent event) {
        }
    }
}

It is now necessary to develop a test program. The following six lines will be crucial in the event. They build a JList component, attach it to the JScrollPane component, and then attach a text box to it as seen in the code:

FilteringJList list = new FilteringJList();
JScrollPane pane=new JScrollPane(list);
frame.add(pane,BorderLayout.CENTER);
JTextField text=new JTextField();list.installJTextField(text);
frame.add(text,BorderLayout.NORTH);

To the model, new components are introduced in the program’s primary body. The model shown below includes a list of Christmas gifts, the names of Santa’s reindeer, the names of London Underground lines, and the letters of the Greek alphabet.

package org.kodejava.swing;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import java.awt.BorderLayout;
import java.awt.EventQueue;

public class JListFiltersDemo {
    public static void main(String[] args) {
        Runnable runner = () -> {
            JFrame frame = new JFrame("Filtering List");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            FilteringJList list = new FilteringJList();
            JScrollPane pane = new JScrollPane(list);
            frame.add(pane, BorderLayout.CENTER);
            JTextField text = new JTextField();
            list.installJTextField(text);
            frame.add(text, BorderLayout.NORTH);
            String[] elements = {
                    "Partridge in a pear tree", "Turtle Doves", "French Hens",
                    "Calling Birds", "Golden Rings", "Geese-a-laying",
                    "Swans-a-swimming", "Maids-a-milking", "Ladies dancing",
                    "Lords-a-leaping", "Pipers piping", "Drummers drumming",
                    "Dasher", "Dancer", "Prancer", "Vixen", "Comet", "Cupid",
                    "Donner", "Blitzen", "Rudolf", "Bakerloo", "Center",
                    "Circle", "District", "East London", "Hammersmith and City",
                    "Jubilee", "Metropolitan", "Northern", "Piccadilly Royal",
                    "Victoria", "Waterloo and City", "Alpha", "Beta", "Gamma",
                    "Delta", "Epsilon", "Zeta", "Eta", "Theta", "Iota", "Kappa",
                    "Lambda", "Mu", "Nu", "Xi", "Omicron", "Pi", "Rho", "Sigma",
                    "Tau", "Upsilon", "Phi", "Chi", "Psi", "Omega"};
            for (String element : elements) {
                list.addElement(element);
            }
            frame.setSize(500, 500);
            frame.setVisible(true);
        };
        EventQueue.invokeLater(runner);
    }
}
Filtering JList Component Models Demo

Filtering JList Component Models Demo

Because this filtering strategy is based on the JList component and its accompanying JTextField component, it will operate successfully if your list’s entries are appropriately displayed when you use the function toString(). Creating a Filter interface that is provided to the model when filtering operations are performed might be useful for doing more complicated filtering tasks.

In this example, the only item that is not addressed is the process of selection. By default, when the contents of the model list change, the JList does not update the selection of the model list. Filtering may be used to either retain the chosen item or emphasize the first item in the list, depending on the desired behavior.

Even though the original JList component does not explicitly offer the functionality, there are techniques to implement filtering. Overriding the getNextMatch() function allows you to alter the default behavior if you so want.

Basic Operators in Java

This article covers basic operators of Java syntax, and how they function. By thorough discussion and coding examples, you’ll be able to use basic operators in your programs like a pro.

What are basic operators?

Java provides different sets of operators to perform simple computations like addition/ subtraction and other advanced operators for decision-making or individual bitwise calculations.

Here are some major categories of operators

  • Arithmetic Operators (+, -, *, /)
  • Relational Operators (==, !=)
  • Logical Operators (&&, ||)
  • Assignment Operators (=, +=, -=)
  • Unary Operators (pre/post-fix)
  • Shift Operators (>>, << )
  • Bitwise Operators (&, |, ^)
  • Ternary/Conditional Operator (?:)
  • Misc Operators

The scope of this article encompass arithmetic, relational and logical operators only.

Arithmetic Operators

You can use basic arithmetic operators to perform a mathematical calculation and impact the value of any variable. Let’s see how it works in Java.

package com.basicoperators.core;

public class ArithmeticOperators {
    public static void main(String[] args) {
        // Addition 
        int apples = 5;
        int oranges = 7;
        int totalFruits = apples + oranges;

        System.out.println("\n-------------Addition---------------- " );
        System.out.println("Apples: " + apples);
        System.out.println("Oranges: " + oranges);
        System.out.println("Total Fruits: " + totalFruits);

        // Subtraction      
        int totalBananas = 24;
        int bananasSold = 12;
        int bananasLeft = totalBananas - bananasSold;

        System.out.println("\n----------------Subtraction--------------- " );
        System.out.println("Total Bananas: " + totalBananas);
        System.out.println("Bananas Sold: " + bananasSold);
        System.out.println("Bananas Left: " + bananasLeft);

        // Multiplication   
        int weeks = 3;
        int daysInAWeek = 7;
        int totalNumberOfDays = weeks * daysInAWeek;

        System.out.println("\n--------------Multiplication-------------- " );
        System.out.println("Days In A Week: " + daysInAWeek);
        System.out.println("Days In A Week: " + daysInAWeek);
        System.out.println("Total Number Of Days: " + totalNumberOfDays);

        // Division
        int totalMinutesConsumed = 420;
        int minutesInOneHour = 60;
        int numOfHours = totalMinutesConsumed / minutesInOneHour;

        System.out.println("\n----------------Division---------------- " );

        System.out.println("Total Minutes: " + totalMinutesConsumed);
        System.out.println("Minutes In One Hour: " + minutesInOneHour);
        System.out.println("Num Of Hours: " + numOfHours);    
    }
}

Output

----------------------Addition---------------------- 
Apples: 5
Oranges: 7
Total Fruits: 12

---------------------Subtraction--------------------- 
Total Bananas: 24
Bananas Sold: 12
Bananas Left: 12

--------------------Multiplication------------------- 
Days In A Week: 7
Days In A Week: 7
Total Number Of Days: 21

----------------------Division---------------------- 
Total Minutes Consumed: 420
Minutes In One Hour: 60
Num Of Hours: 7

Relational Operators

As the name implies, relational operators define the relationship of one instance with another. This means you can compare two numbers and see what relationship do they share. If they are equal to each other, one is greater than or smaller than the other number. Like 2 is less than 3. According to Java syntax, both instances should be of the same data type. For example, you can not compare if an integer is less than a string. Here is a small snippet explaining how you can use basic relational operators in Java.

package com.basicoperators.core;

public class RelationalOperators {
    public static void main(String[] args) {
        int even = 2;
        int odd = 3;

        System.out.println("Even = " + even);
        System.out.println("Odd = " + odd);

        // prints if even is equal to odd
        boolean check = even == odd;
        System.out.println("Is Even equal to Odd? " + check);

        // prints if even is not equal to odd
        check = even != odd;
        System.out.println("Is Even not equal to Odd? " + check);

        // prints if even is greater than odd
        check = even > odd;
        System.out.println("Is Even greater than Odd? " + check);

        // prints if even is less than odd
        check = even < odd;
        System.out.println("Is Even less than Odd? " + check);

        // prints if even is greater than equal to odd
        check = even >= odd;
        System.out.println("Is Even greater than equal to Odd? " + check);

        // prints if even is less than equal to odd
        check = even <= odd;
        System.out.println("Is Even less than equal to Odd? " + check);
    }
}

Output

Even = 2
Odd = 3
Is Even equal to Odd? false
Is Even not equal to Odd? true
Is Even greater than Odd? false
Is Even less than Odd? true
Is Even greater than equal to Odd? false
Is Even less than equal to Odd? true

Logical Operators

Logical Operators in Java are used for decision-making. They allow the programmer to test if the combination of given expressions are true or false. Based on the result of your expression, you can make a decision.

  • AND – returns “true” only if both expressions are true
  • OR – returns “true” if any of the given expressions is true
  • NOT – returns the “inverse” of any given boolean expression

For your better understanding, let’s look at the following snippet.

package com.basicoperators.core;

public class LogicalOperators {
    public static void main(String[] args) {
        String myPet1 = "doggo";
        String myPet2 = "kitty";

        System.out.println("Pet1: " + myPet1);
        System.out.println("Pet2: " + myPet2);

        // implements AND
        boolean check = myPet1.equals("doggo") && myPet2.equals("kitty");
        // returns true only when both conditions are true
        System.out.println("Does my first pet name \"doggo\", and second one \"kitty\"? " + check);

        check = myPet1.equals("dog") && myPet2.equals("kitty");
        // returns "false" even if single condition is false 
        // remember these conditions are case sensitive
        System.out.println("Does my first pet name \"dog\", and second one \"kitty\"? " + check);

        // implements OR
        check = myPet1.equals("doggo") || myPet2.equals("lion");
        // returns "true" even when single condition is true
        System.out.println("Does any of my pet name \"doggo\"? " + check);

        check = myPet1.equals("cat") || myPet2.equals("tiger");
        // returns "false" because both conditions are false
        System.out.println("Does any of my pet name \"tiger\"? " + check);

        // implements NOT
        check = !(myPet1.equals("bingo") && myPet2.equals("kate"));
        // returns "true" when both conditions are true (inverse of statement)
        System.out.println("Does my first pet name \"bingo\", and second one \"kate\"? " + check);

        check = !(myPet1.equals("doggo") && myPet2.equals("kitty"));
        // returns "false" because both conditions are true
        System.out.println("Does my first pet name \"doggo\", and second one \"kitty\"? " + check);
    }
}

Output

Pet1: doggo
Pet2: kitty
Does my first pet name "doggo", and second one "kitty"? true
Does my first pet name "dog", and second one "kitty"? false
Does any of my pet name "doggo"? true
Does any of my pet name "tiger"? false
Does my first pet name "bingo", and second one "kate"? true
Does my first pet name "doggo", and second one "kitty"? false

Conclusion

The basic operators in Java are pretty simple to learn and easy to use. You might get overwhelmed by studying the different operators all at once. However, we recommend you practicing one set at a time. This way, you’ll master all of them soon. As always, you’re welcome to plug-in in case of any confusion. Happy learning!