Skip to main content

7.2 Functional Programming and Collections

Working with Selected Classes from the Java API

1. Course Overview

This course covers key classes from the Java API, focusing on commonly used data structures like ArrayList, lambda expressions, working with String and StringBuilder, and handling dates and times. By the end of the course, you will understand how to manipulate these classes effectively in Java applications.


2. Working with ArrayList

Creating ArrayLists

An ArrayList is a resizable array from the java.util package. Unlike arrays, it can grow in size dynamically. To create an ArrayList, you use the ArrayList class.

Example:

ArrayList<String> fruits = new ArrayList<>();

Adding and Removing Elements

You can add elements to an ArrayList using the add() method, and remove elements using the remove() method.

Example:

fruits.add("Apple");
fruits.remove("Apple");

Inspecting and Traversing ArrayLists

You can check the size of an ArrayList using size(), and traverse it using a for-each loop or an iterator.

Example:

for (String fruit : fruits) {
System.out.println(fruit);
}

Autoboxing with ArrayLists

Java supports autoboxing, which allows primitive types to be automatically converted to their corresponding wrapper class when used in an ArrayList.

Example:

ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(5); // Autoboxes the int 5 to Integer

3. Working with Lambda Predicates

Lambda Functional Interfaces

A functional interface is an interface with a single abstract method. Lambdas are used to provide implementations for these interfaces in a concise manner.

Example:

@FunctionalInterface
interface Printer {
void print(String message);
}

Printer printer = (message) -> System.out.println(message);

Lambda Expressions

Lambda expressions are a way to create anonymous methods in Java, making your code shorter and more readable.

Example:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
numbers.forEach((n) -> System.out.println(n));

Lambda Predicates

A Predicate is a functional interface that takes an argument and returns a boolean. It is often used to filter data in Java.

Example:

Predicate<Integer> isEven = (n) -> n % 2 == 0;
System.out.println(isEven.test(4)); // true

4. Working with Strings and StringBuffer

The Immutable String

In Java, String objects are immutable, meaning once they are created, their value cannot be changed. Any modification results in the creation of a new String object.

String Concatenation

Concatenating strings can be done using the + operator or the concat() method.

Example:

String fullName = "John" + " " + "Doe";

String Methods, Part 1

Some common string methods include length(), charAt(), and substring().

Example:

String name = "John";
int length = name.length();
char initial = name.charAt(0);

String Methods, Part 2

Additional methods like indexOf(), replace(), and toLowerCase() are frequently used.

Example:

String text = "Hello World";
text = text.replace("World", "Java");

StringBuilder, Part 1

StringBuilder is a mutable sequence of characters, which means it can be modified without creating new objects. It's more efficient for repeated string operations.

Example:

StringBuilder sb = new StringBuilder("Hello");
sb.append(" World");

StringBuilder, Part 2

Other StringBuilder methods include insert(), delete(), and reverse().

Example:

sb.insert(5, " Java");
sb.reverse();

5. Working with Dates and Times

Create Dates and Times

The LocalDate, LocalTime, and LocalDateTime classes from the java.time package are used to represent dates and times in Java.

Example:

LocalDate date = LocalDate.now();
LocalTime time = LocalTime.now();

Calculate Dates and Times

You can perform date and time calculations using methods like plusDays() and minusMonths().

Example:

LocalDate futureDate = date.plusDays(10);

Periods and Durations

Period is used to represent the amount of time between two dates, while Duration represents the time between two instants or times.

Example:

Period period = Period.between(LocalDate.of(2022, 1, 1), LocalDate.now());

Format Dates and Times

You can format dates and times using the DateTimeFormatter class.

Example:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
String formattedDate = date.format(formatter);

Conclusion

In this tutorial, we explored key classes from the Java API, focusing on ArrayList, lambda expressions, String, StringBuilder, and date/time manipulation. These are fundamental building blocks for Java programming, and mastering them will help you write efficient and effective Java code.