Collection and Layered Architecture Notes
Collection and Layered Architecture Notes
1. Lambda Expressions
Syntax:
Example:
2. Functional Interfaces
Example:
@FunctionalInterface
interface MyFunctionalInterface {
void doSomething();
o Predicate<T>
o Function<T, R>
o Supplier<T>
o Consumer<T>
3. Stream API
Usage: You can chain operations like filter(), map(), and reduce(),
making operations on collections easier.
Example:
.collect(Collectors.toList());
Example:
interface MyInterface {
package sample;
public interface Shape {
public float calculateArea();
default void display() {
System.out.println("In inteface");
}
}
package sample;
float PI=3.14f;
public float calculateArea();
/*
*/
return 3.14f;
return true;
package sample;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
Shape shape;
shape=new Circle();
shape.describeShape();
shape=new Square();
shape.describeShape();
5. Method References
Types:
Example:
names.forEach((str)->System.out.ptintln(str))
6. Optional Class
Usage:
optionalName.ifPresent(System.out::println);
System.out.println(str.orElse("aaa"));
}
public static Optional<String> getName() {
String name=null;
Scanner input=new Scanner(System.in);
name=input.nextLine();
if(name.matches("[a-zA-Z ]{1,}")) {
name=name+" is valid ";
}else {
name=null;
}
Optional<String>
op=Optional.ofNullable(name);
return op;
}
}
Here are scenarios where Optional can be used, along with examples:
When a method might return a value or might return null, you can use
Optional to make this clear. Instead of returning null, you return an
empty Optional.
Example:
import java.util.Optional;
this.email = email;
System.out.println(userWithMail.getEmail().orElse("Email not
provided"));
System.out.println(userWithoutMail.getEmail().orElse("Email not
provided"));
Optional helps you avoid excessive null checks and handle the absence
of values more cleanly.
Example:
if (optionalValue.isPresent()) {
You can provide a default value when the Optional is empty using the
orElse() or orElseGet() methods.
Example:
import java.util.Optional;
}
}
You can throw an exception when a value is not present by using the
orElseThrow() method.
Example:
import java.util.Optional;
System.out.println(result);
6. Filtering Optionals
You can filter the value inside an Optional based on a condition, which
returns the original Optional if the condition is met or an empty
Optional otherwise.
Example:
import java.util.Optional;
Example:
System.out.println(age.getYears());
Classes:
o LocalDate
o LocalTime
o LocalDateTime
o ZonedDateTime
o Duration, Period
8. Collectors
Example:
.collect(Collectors.joining(", "));
Let's take a list of strings and create a map where the key is the string
itself, and the value is the length of the string.
import java.util.*;
import java.util.stream.Collectors;
Let's take a list of custom Person objects and collect them into a map
where the key is the id and the value is the name.
import java.util.*;
import java.util.stream.Collectors;
class Person {
int id;
String name;
public Person(int id, String name) {
this.id = id;
this.name = name;
return id;
return name;
);
.collect(Collectors.toMap(Person::getId, Person::getName));
}
Explanation: The Person object's id is used as the key, and the
name is used as the value in the resulting map.
7. ForEach() Method
Example:
Scenario:
You have a list of Transaction objects, each with an amount. You want to
find the transaction with the highest amount.
import java.util.*;
import java.util.stream.Collectors;
class Transaction {
int id;
double amount;
this.id = id;
this.amount = amount;
return id;
return amount;
}
);
.max(Comparator.comparingDouble(Transaction::getAmount));
Explanation:
Scenario:
You have a list of products, and you want to partition them into two
groups: one group for products that cost more than $100 and another for
products that cost less than or equal to $100.
import java.util.*;
import java.util.stream.Collectors;
class Product {
String name;
double price;
this.name = name;
this.price = price;
);
Explanation:
partitioningBy() splits the collection into two lists based on whether the
condition price > 100 is true or false.
Scenario:
You have a Department class that contains a list of Employee objects. You
want to extract all unique employee names from all departments.
import java.util.*;
import java.util.stream.Collectors;
class Employee {
String name;
this.name = name;
class Department {
String name;
List<Employee> employees;
this.name = name;
this.employees = employees;
);
.collect(Collectors.toSet());
Explanation:
TreeSet and TreeMap are part of Java’s java.util package and are
implemented using red-black trees, ensuring that elements are
stored in a sorted order.
TreeSet:
o Automatically sorts elements in natural order (or by a custom
comparator).
TreeSet<String> set=new
TreeSet<String>(Comparator.reverseOrder());
set.add("aa");
set.add("mm");
set.add("bb");
System.out.println(set);
TreeMap:
TreeMap methods:
3. Backed Collections
4. Generic Types
Before generics (Java 5), collections used raw types (List, Set)
without type safety.
Mixing generics with legacy code involves using raw types with
generic collections.
Example:
System.out.println(element);
8. Layered Architecture
o Example:
service.execute();
o Example:
o Example:
4. Iterator Pattern:
o Example:
boolean hasNext();
Object next();