Functional Interface in Java
Java Functional Interfaces
A practical guide to lambdas, method references and common functional interfaces in Java.
1. What Is a Functional Interface?
A functional interface has exactly one abstract method, also called a Single Abstract Method (SAM). It can be the target type of a lambda expression or a compatible method reference.
- Default and static methods have implementations and do not count as abstract methods. The
abstractkeyword on an interface's abstract methods is optional. - An abstract method matching a public method of
java.lang.Object, such asequals(Object), does not count toward the functional method. Inherited abstract methods also matter. @FunctionalInterfaceis optional but asks the compiler to check that the interface is functional. The annotation does not itself make an interface functional.
.java file named after its public class; compile with javac FileName.java and run with java ClassName.2. Custom Interface and Lambda
A lambda supplies an instance of a functional interface. You can also pass that behavior as a method argument. Here add is the only functional method.
Example: pass an addition operation
public class AdditionExample {
@FunctionalInterface
interface Addition {
int add(int a, int b);
boolean equals(Object other);
default int addOne(int value) {
return add(value, 1);
}
static String name() {
return "addition";
}
}
static int calculate(int a, int b, Addition operation) {
return operation.add(a, b);
}
public static void main(String[] args) {
Addition sum = (a, b) -> a + b;
System.out.println(calculate(3, 4, sum));
System.out.println(sum.addOne(9));
System.out.println(Addition.name());
}
}
Output:
7
10
addition
@FunctionalInterface.3. Runnable and Threads
Runnable has one abstract method, run(). Existing interfaces such as Runnable can also be used with lambdas. In this example, join() waits for the worker to finish.
public class RunnableExample {
public static void main(String[] args) throws InterruptedException {
Runnable task = () -> System.out.println("New thread created Lambda");
Thread worker = new Thread(task);
worker.start();
worker.join();
}
}
Output:
New thread created Lambda
4. Consumer and Method References
Consumer<T> accepts one input and returns no result from accept(T). It is commonly used for printing or other side effects. IntConsumer, LongConsumer and DoubleConsumer are primitive specializations.
Example: sum a list and print a message
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
public class ConsumerExample {
static void printSum(List<Integer> values) {
int sum = values.stream().mapToInt(Integer::intValue).sum();
System.out.println("Sum of list values: " + sum);
}
public static void main(String[] args) {
List<Integer> values = Arrays.asList(10, 20, 30, 40);
Consumer<List<Integer>> sum = ConsumerExample::printSum;
sum.accept(values);
Consumer<String> print = System.out::println;
print.accept("javaA143mk");
}
}
Output:
Sum of list values: 100
javaA143mk
:: is method-reference syntax. The referenced method must be compatible with the target functional interface's parameters and return type.
5. Predicate and Class Implementation
Predicate<T> tests an input and returns a boolean from test(T). Combine conditions with and, or and negate. It can be implemented by a lambda or a regular class.
import java.util.function.Predicate;
public class PredicateExample {
static class Adult implements Predicate<Integer> {
@Override
public boolean test(Integer age) {
return age >= 18;
}
}
public static void main(String[] args) {
Predicate<Integer> adult = new Adult();
Predicate<Integer> under65 = age -> age < 65;
System.out.println(adult.test(10));
System.out.println(adult.and(under65).test(25));
System.out.println(adult.negate().test(10));
}
}
Output:
false
true
true
NullPointerException during unboxing. Validate inputs as required by your application.6. Other Common Functional Interfaces
| Interface | Abstract method | Typical use |
|---|---|---|
| Function<T, R> | apply(T) | Transform an input into a result. |
| Supplier<T> | get() | Supply a value without an input. |
| Consumer<T> | accept(T) | Perform a side effect with an input; return no value. |
| Predicate<T> | test(T) | Decide true or false about an input. |
| UnaryOperator<T> | apply(T) | Transform one value with the same input and result type. |
| BinaryOperator<T> | apply(T, T) | Combine two values of the same type into a result of that type. |
Other examples include Runnable, Callable, Comparator, Comparable and ActionListener. Function, Supplier, Consumer and Predicate are in java.util.function.
Example: Function, Supplier and BinaryOperator
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
public class FunctionExample {
public static void main(String[] args) {
Function<String, Integer> length = String::length;
Supplier<String> greeting = () -> "Java";
BinaryOperator<Integer> sum = Integer::sum;
System.out.println(length.apply(greeting.get()));
System.out.println(sum.apply(2, 3));
}
}
Output:
4
5
7. Marker Interfaces: A Different Concept
A marker interface is used to mark a type and typically declares no methods. A functional interface has one abstract method, so an empty marker interface is not itself a functional interface and cannot be the target of a lambda.
Example: recognize a marked type
public class MarkerExample {
interface Car { }
interface Engine { }
static class Vehicle implements Car { }
static class EngineStatus implements Engine { }
public static void main(String[] args) {
Object vehicle = new Vehicle();
Object status = new EngineStatus();
System.out.println(vehicle instanceof Car);
System.out.println(status instanceof Engine);
}
}
Output:
true
true
Serializable, Cloneable and Remote are well-known marker interfaces. Their meaning is defined by the relevant Java APIs; declaring your own marker does not automatically add behavior. For example, implementing Cloneable alone does not provide a public clone() method.
For more details, see the FunctionalInterface API and java.util.function documentation.
Map Interfaces
Architecture of Map interface:
Hashtable: Hashtable is similar to HashMap except it is synchronized.
Output: String, hashtable Contains :{Total=654, Sum=67}
Integer, hashtable Contains :{3=4, 1=2}
LinkedHashMap: It is Hashtable and LinkedList implementation of map interface. LinkedHashMap has a doublelinkedlist Running through all its elements.
Output: Put, LinkedHashMap Contains :{Hi=1, manoj=2, welcom=3}
Remove, LinkedHashMap Contains :{Hi=1, welcom=3}
HashMap: A HashMap is a Hashtable implementation of map interface, unlike HashMap it contains null keys and values. HashMap does not guarantee that the order of the objects will remain same over the time.
Output: Put, HashMap Contains :{Hi=1, welcom=3, manoj=2}
Remove, HashMap Contains :{Hi=1, welcom=3}
TreeMap: A TreeMap Provides red-block tree based implementation of map interface.
Output: Put, treeMap Contains :{Hi=1, manoj=2, welcom=3}
Remove, treeMap Contains :{Hi=1, welcom=3}
Collection Framework Implementations
Java Collections Framework
A practical guide to collection interfaces, implementations and everyday development scenarios.
1. Architecture and Interfaces
The Java Collections Framework provides interfaces, implementations and utility methods for storing and processing groups of objects. Most are in java.util; concurrent implementations are in java.util.concurrent.
- Iterable supplies an iterator and enables the enhanced
forloop. Collection extends it and defines operations such asadd,remove,containsandsize. - List is an ordered, indexed sequence that permits duplicates. Its implementations include
ArrayList,LinkedListandVector. - Queue holds elements for processing; Deque supports both ends.
LinkedListimplements both List and Deque. - Set rejects duplicates.
SortedSetadds sorted order;NavigableSetadds navigation methods such asfloorandceiling.TreeSetimplements both. - Map stores key-value pairs. It is part of the framework but does not extend
Collection; its views, such askeySet(), are collections.
javac FileName.java and run with java ClassName.2. Choose the Right Collection
| Need | Typical choice | Important behavior |
|---|---|---|
| Indexed sequence, duplicates allowed | ArrayList | Insertion order; fast indexed access; middle inserts shift elements. |
| Items at both ends | ArrayDeque | Efficient queue or stack; no null elements. |
| FIFO work queue | ArrayDeque | Add at the tail and remove from the head. |
| Next item by priority | PriorityQueue | Head is the least element by natural order or comparator; iteration is not sorted. |
| Unique values | HashSet | No guaranteed iteration order; permits one null. |
| Unique values in insertion order | LinkedHashSet | Preserves insertion order; permits one null. |
| Unique values in sorted order | TreeSet | Uses natural order or a comparator to order and identify duplicates. |
| Find a value by key | HashMap | No guaranteed iteration order; permits one null key and null values. |
| Sorted keys or range queries | TreeMap | Keys are sorted; keys must be comparable by its ordering. |
Program to an interface when practical, for example List<String> names = new ArrayList<>();. Select the implementation according to ordering, operations, null handling and concurrency needs.
3. List: ArrayList, LinkedList and Vector
ArrayList uses a resizable array and is a good default for indexed access and appending. LinkedList is a doubly linked list: operations at its ends are efficient, but indexed access requires traversal. Vector is a legacy synchronized list; its individual methods are synchronized, not a complete solution for compound actions or iteration. Stack extends Vector; prefer Deque for a new stack.
Example: add, update, remove and copy
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Vector;
public class ListExample {
public static void main(String[] args) {
List<String> names = new ArrayList<>(Arrays.asList("Ana", "Ben", "Ana"));
names.add("Dev");
names.set(1, "Bea");
names.remove("Ana"); // removes the first matching value
System.out.println(names);
List<String> copy = new ArrayList<>(names);
List<String> destination = new ArrayList<>(Arrays.asList("-", "-", "-", "extra"));
Collections.copy(destination, copy);
System.out.println(destination);
List<String> linked = new LinkedList<>(copy);
List<String> legacy = new Vector<>(linked);
System.out.println(legacy);
}
}
Output:
[Bea, Ana, Dev]
[Bea, Ana, Dev, extra]
[Bea, Ana, Dev]
Collections.copy(destination, source) replaces existing positions; the destination must already have at least as many elements as the source, or it throws IndexOutOfBoundsException. A new ArrayList<>(source) makes a shallow copy and is usually simpler.Lists store references: a shallow copy has independent list structure but shares the contained objects. In List<Integer>, remove(1) removes index 1; use remove(Integer.valueOf(1)) to remove the value.
4. Queue, Deque and PriorityQueue
For an empty queue, poll() and peek() return null, while remove() and element() throw NoSuchElementException. For capacity-limited queues, offer() can return false when insertion fails; add() throws instead. Check the concrete implementation's contract.
ArrayDeque is a resizable-array implementation for FIFO queues and LIFO stacks. It does not accept null. LinkedList also implements Deque, but avoid null in queues because null is the empty-result sentinel. PriorityQueue removes the least element first by default, not necessarily the earliest inserted item.
Example: FIFO, stack and priority
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.PriorityQueue;
import java.util.Queue;
public class QueueExample {
public static void main(String[] args) {
Queue<String> tasks = new ArrayDeque<>();
tasks.offer("build");
tasks.offer("test");
System.out.println(tasks.poll());
System.out.println(tasks.peek());
Deque<String> history = new ArrayDeque<>();
history.push("first");
history.push("second");
System.out.println(history.pop());
Queue<Integer> priority = new PriorityQueue<>();
priority.offer(30);
priority.offer(10);
priority.offer(20);
while (!priority.isEmpty()) {
System.out.print(priority.poll() + " ");
}
System.out.println();
}
}
Output:
build
test
second
10 20 30
For a max-priority queue use new PriorityQueue<>(Collections.reverseOrder()). Iterating or printing a priority queue does not guarantee sorted order; poll elements to process them in priority order.
5. Set: HashSet, LinkedHashSet and TreeSet
Sets keep unique elements. HashSet does not guarantee iteration order, LinkedHashSet preserves insertion order, and TreeSet maintains sorted order. A TreeSet uses its comparator or natural ordering to decide whether two elements are duplicates.
Example: deduplication and sorted ranges
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.NavigableSet;
import java.util.Set;
import java.util.TreeSet;
public class SetExample {
public static void main(String[] args) {
Set<String> unique = new HashSet<>(Arrays.asList("Java", "SQL", "Java"));
System.out.println(unique.size());
System.out.println(unique.contains("Java"));
Set<String> ordered = new LinkedHashSet<>(Arrays.asList("Java", "SQL", "Java"));
System.out.println(ordered);
NavigableSet<Integer> scores = new TreeSet<>(Arrays.asList(30, 10, 20, 20));
System.out.println(scores);
System.out.println(scores.ceiling(15));
System.out.println(scores.subSet(10, true, 30, false));
}
}
Output:
2
true
[Java, SQL]
[10, 20, 30]
20
[10, 20]
subSet returns a backed view, not an independent copy. HashSet and LinkedHashSet allow one null; with natural ordering, TreeSet rejects null. A custom comparator must explicitly support null if it is needed.
6. Map and Key-Value Lookups
Each key has at most one mapped value. HashMap is a common general-purpose choice, LinkedHashMap normally preserves insertion order, and TreeMap sorts keys. An access-order LinkedHashMap is also useful for an LRU-style cache with an appropriate eviction policy.
Example: count values and sort keys
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class MapExample {
public static void main(String[] args) {
Map<String, Integer> counts = new HashMap<>();
for (String word : Arrays.asList("java", "sql", "java")) {
counts.merge(word, 1, Integer::sum);
}
System.out.println(counts.getOrDefault("java", 0));
System.out.println(counts.getOrDefault("missing", 0));
System.out.println(new TreeMap<>(counts));
}
}
Output:
2
0
{java=2, sql=1}
get(key) returning null can mean either a missing key or a key mapped to null. Use containsKey when that distinction matters. Map views such as keySet() and entrySet() are backed by the map.
7. Iteration, Copying and Sorting
Use an enhanced for loop for reading. To remove during iteration, use that iterator's remove(), or use removeIf when appropriate. Modifying many ordinary collections structurally through another path during iteration may throw ConcurrentModificationException; fail-fast detection is best effort, not a thread-safety guarantee.
Example: safe removal, sorted copy and read-only view
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
public class IterationExample {
public static void main(String[] args) {
List<String> items = new ArrayList<>(Arrays.asList("pear", "apple", "pear"));
Iterator<String> it = items.iterator();
while (it.hasNext()) {
if (it.next().equals("pear")) {
it.remove();
}
}
items.add("banana");
List<String> sorted = new ArrayList<>(items);
Collections.sort(sorted);
List<String> readOnly = Collections.unmodifiableList(items);
items.add("cherry");
System.out.println(sorted);
System.out.println(readOnly);
}
}
Output:
[apple, banana]
[apple, banana, cherry]
An unmodifiable view rejects changes through the view but reflects changes to its backing list. For an independent unmodifiable shallow snapshot in Java 8, use Collections.unmodifiableList(new ArrayList<>(items)). Java 10 adds List.copyOf, which rejects null elements. Arrays.asList returns a fixed-size list backed by the array; subList is also a backed view.
8. Equality, Nulls and Common Mistakes
- Hash-based collections: implement
equalsandhashCodeconsistently for custom keys and set elements. Equal objects must have equal hash codes. Do not mutate fields used in equality or hashing while an object is a key or set member. - Sorted collections: the comparator must define a consistent ordering. If it returns zero for different objects, a TreeSet treats them as the same element. Use an ordering consistent with
equalswhen normal Set/Map equality behavior is needed. - Generics: prefer
List<String>to rawListfor compile-time type safety. Use wrapper types such asInteger, not primitiveint, as type arguments. - Null policies differ: ArrayList and LinkedList permit null; ArrayDeque and PriorityQueue do not. ConcurrentHashMap allows neither null keys nor null values. Check the chosen implementation rather than assuming a framework-wide rule.
- Unmodifiable versus immutable: an unmodifiable collection can still contain mutable objects; a view may change when its backing collection changes.
9. Thread Safety and Concurrent Collections
Most general-purpose collections, including ArrayList, HashMap and HashSet, are not thread-safe for concurrent modification. Options include external locking, synchronized wrappers or a concurrent collection selected for the workload.
ConcurrentHashMapsupports concurrent access and atomic operations such asmerge. Its iterators are weakly consistent, not a snapshot.CopyOnWriteArrayListcopies its array on mutation and provides snapshot iterators; it can suit read-heavy, rarely modified lists but is expensive for frequent writes.BlockingQueueimplementations such asArrayBlockingQueuesupport producer-consumer workflows.putandtakecan block and throwInterruptedException.- When iterating a
Collections.synchronizedList, synchronize on the returned list for the entire iteration; individual synchronized method calls do not make a multi-step operation atomic.
Example: atomic counting and snapshot iteration
import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
public class ConcurrentExample {
public static void main(String[] args) {
Map<String, Integer> counts = new ConcurrentHashMap<>();
counts.merge("requests", 1, Integer::sum);
counts.merge("requests", 1, Integer::sum);
System.out.println(counts.get("requests"));
CopyOnWriteArrayList<String> listeners =
new CopyOnWriteArrayList<>(Arrays.asList("first"));
Iterator<String> snapshot = listeners.iterator();
listeners.add("second");
while (snapshot.hasNext()) {
System.out.println(snapshot.next());
}
System.out.println(listeners);
}
}
Output:
2
first
[first, second]
This example demonstrates the APIs; real concurrent behavior depends on thread coordination and the atomicity of the specific operations used.
10. Performance and Practical Scenarios
The following are typical operation costs, not performance guarantees for every workload. Hash-based costs assume well-distributed hashes; amortized costs average occasional resizing over many operations.
| Implementation | Typical costs | Use case |
|---|---|---|
| ArrayList | Index access O(1); append amortized O(1); middle insertion/removal O(n). | Ordered results, indexed access. |
| LinkedList | End operations O(1); indexed access O(n). | List/deque operations at both ends. |
| ArrayDeque | End insertion/removal amortized O(1). | Request queue, undo stack, breadth-first traversal. |
| HashSet / HashMap | Add, lookup and removal expected O(1). | Deduplication or lookup by key. |
| TreeSet / TreeMap | Add, lookup and removal O(log n). | Sorted values, keys and range queries. |
| PriorityQueue | Offer and poll O(log n); peek O(1). | Process the highest- or lowest-priority task next. |
Choose based on actual access patterns, ordering requirements, memory use and synchronization. Measure realistic workloads before optimizing. For details and implementation-specific contracts, see the Java Collections API documentation and concurrent utilities.

