Define a generic Repository<T, ID> interface (save, findById as Optional, findAll, delete) and a default count(); implement an in-memory repository for students and use it from a service.
Solution
Main.java
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
interface Repository<T, ID> {
T save(T entity);
Optional<T> findById(ID id);
List<T> findAll();
boolean delete(ID id);
default int count() { return findAll().size(); }
}
class InMemoryRepository<T, ID> implements Repository<T, ID> {
private final Map<ID, T> store = new LinkedHashMap<>();
private final Function<T, ID> idOf;
InMemoryRepository(Function<T, ID> idOf) { this.idOf = idOf; }
public T save(T e) { store.put(idOf.apply(e), e); return e; }
public Optional<T> findById(ID id) { return Optional.ofNullable(store.get(id)); }
public List<T> findAll() { return new ArrayList<>(store.values()); }
public boolean delete(ID id) { return store.remove(id) != null; }
}
record Student(int roll, String name) { }
public class Main {
public static void main(String[] args) {
Repository<Student, Integer> repo = new InMemoryRepository<>(Student::roll);
repo.save(new Student(1, "Asha"));
repo.save(new Student(2, "Ravi"));
repo.save(new Student(1, "Asha K")); // same id → replaced
System.out.println(repo.count() + " " + repo.findAll());
System.out.println(repo.findById(2).map(Student::name).orElse("none") + " " + repo.findById(9).map(Student::name).orElse("none"));
System.out.println(repo.delete(2) + " " + repo.delete(2) + " " + repo.count());
}
}
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!