Powered by Blogger.

Functional Interface in Java

1 comment :

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 abstract keyword on an interface's abstract methods is optional.
  • An abstract method matching a public method of java.lang.Object, such as equals(Object), does not count toward the functional method. Inherited abstract methods also matter.
  • @FunctionalInterface is optional but asks the compiler to check that the interface is functional. The annotation does not itself make an interface functional.
Use Java 8 or later. Save each complete example in a .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
Adding a second distinct abstract method makes this interface non-functional, and compilation fails with @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
Passing a null age to this example causes a NullPointerException during unboxing. Validate inputs as required by your application.

6. Other Common Functional Interfaces

InterfaceAbstract methodTypical 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


The Map interface maps unique keys to values. A key is an object that you use to retrieve a value at a later date.
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.

Java collection hierarchy showing List, Queue, Deque and Set implementations
  • Iterable supplies an iterator and enables the enhanced for loop. Collection extends it and defines operations such as add, remove, contains and size.
  • List is an ordered, indexed sequence that permits duplicates. Its implementations include ArrayList, LinkedList and Vector.
  • Queue holds elements for processing; Deque supports both ends. LinkedList implements both List and Deque.
  • Set rejects duplicates. SortedSet adds sorted order; NavigableSet adds navigation methods such as floor and ceiling. TreeSet implements both.
  • Map stores key-value pairs. It is part of the framework but does not extend Collection; its views, such as keySet(), are collections.
Version: The complete examples below use Java 8 or later. Save each program in a file named after its public class, then compile with javac FileName.java and run with java ClassName.

2. Choose the Right Collection

NeedTypical choiceImportant behavior
Indexed sequence, duplicates allowedArrayListInsertion order; fast indexed access; middle inserts shift elements.
Items at both endsArrayDequeEfficient queue or stack; no null elements.
FIFO work queueArrayDequeAdd at the tail and remove from the head.
Next item by priorityPriorityQueueHead is the least element by natural order or comparator; iteration is not sorted.
Unique valuesHashSetNo guaranteed iteration order; permits one null.
Unique values in insertion orderLinkedHashSetPreserves insertion order; permits one null.
Unique values in sorted orderTreeSetUses natural order or a comparator to order and identify duplicates.
Find a value by keyHashMapNo guaranteed iteration order; permits one null key and null values.
Sorted keys or range queriesTreeMapKeys 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]
Copying: 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 equals and hashCode consistently 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 equals when normal Set/Map equality behavior is needed.
  • Generics: prefer List<String> to raw List for compile-time type safety. Use wrapper types such as Integer, not primitive int, 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.
Do not rely on the iteration order of HashSet, HashMap or PriorityQueue. If order is part of the requirement, choose an implementation that explicitly guarantees it.

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.

  • ConcurrentHashMap supports concurrent access and atomic operations such as merge. Its iterators are weakly consistent, not a snapshot.
  • CopyOnWriteArrayList copies its array on mutation and provides snapshot iterators; it can suit read-heavy, rarely modified lists but is expensive for frequent writes.
  • BlockingQueue implementations such as ArrayBlockingQueue support producer-consumer workflows. put and take can block and throw InterruptedException.
  • 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.

ImplementationTypical costsUse case
ArrayListIndex access O(1); append amortized O(1); middle insertion/removal O(n).Ordered results, indexed access.
LinkedListEnd operations O(1); indexed access O(n).List/deque operations at both ends.
ArrayDequeEnd insertion/removal amortized O(1).Request queue, undo stack, breadth-first traversal.
HashSet / HashMapAdd, lookup and removal expected O(1).Deduplication or lookup by key.
TreeSet / TreeMapAdd, lookup and removal O(log n).Sorted values, keys and range queries.
PriorityQueueOffer 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.