LearnFrenzy
Sign in Take a free test

Interfaces · Interfaces Programs · Question 8

Repository interface with two implementations in Java Solution, output & explanation

  • Program
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 8 Back to Exercise

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());
    }
}

Output Verified by compiling and running

2 [Student[roll=1, name=Asha K], Student[roll=2, name=Ravi]]
Ravi none
true false 1

Code written against Repository could switch to a database implementation without change; count() comes free as a default method.

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links