Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to generalize methods using functional Java

Can we reduce code duplication with these methods with the new java functional paradigm? I tried to pass the function as param. But one has Functional and the other BiFunctional. Unable to make it as from below code {1} & {2} are diff JPA queries with different num of method args. I am honestly new to this and appreciate any help.

public long byId(List<Long> ids) {
    Pageable pageRequest = PageRequest.of(0, 10, Sort.Direction.ASC, "id");
    Page<SomeDAO> currentPage = repository.findByIdIn(ids, pageRequest); // {1}

    long totalRecords = 0;
    while (!currentPage.isEmpty()) {
        pageRequest = pageRequest.next();
        totalRecords += currentPage.getContent().size();
        // some BL
        currentPage = repository.findByIdIn(ids, pageRequest); // {1}
    }
    return totalRecords;
}

public long all() {
    Pageable pageRequest = PageRequest.of(0, 10, Sort.Direction.ASC, "id");
    Page<SomeDAO> currentPage = repository.findAll(pageRequest); // {2}

    long totalRecords = 0;
    while (!currentPage.isEmpty()) {
        pageRequest = pageRequest.next();
        totalRecords += currentPage.getContent().size();
        // some BL
        currentPage = repository.findAll(pageRequest);  // {2}
    }
    return totalRecords;
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Use Function.

public long byId(List<Long> ids) {
    return general(pageRequest -> repository.findByIdIn(ids, pageRequest));
}

public long all() {
    return general(pageRequest -> repository.findAll(pageRequest));
}

public long general(Function<Pageable, Page<SomeDAO>> find) {
    Pageable pageRequest = PageRequest.of(0, 10, Sort.Direction.ASC, "id");
    Page<SomeDAO> currentPage = find.apply(pageRequest);

    long totalRecords = 0;
    while (!currentPage.isEmpty()) {
        pageRequest = pageRequest.next();
        totalRecords += currentPage.getContent().size();
        // some BL
        currentPage = find.apply(pageRequest);
    }
    return totalRecords;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading