Search code examples
javaspringjpa

how to distinct below result using java


How to distinct below result using java? My code is as per below:

Page<Object[]> datasetresults=repository.findtest(tid,
                    PageRequest.of(page, per_page, Sort.by(s, sort)));

for (Object[] object : datasetresults.getContent()) {
    if (object[0] instanceof onetable ) {
        onetable onetable = (onetable) object[0];
        TestBean test = new TestBean();
    }   
}

I need to distinct using tid to get one unique result set.


Solution

  • To distinct the results based on the "tid" column and get a unique result set, you can use a Set to keep track of unique tid values while iterating through the datasetresults. Here's how you can modify your code to achieve this:

    Page<Object[]> datasetresults = repository.findtest(tid, PageRequest.of(page, per_page, Sort.by(s, sort)));
    
    // Create a Set to keep track of unique tid values
    Set<Long> uniqueTids = new HashSet<>();
    
    for (Object[] object : datasetresults.getContent()) {
        if (object[0] instanceof onetable && object[1] instanceof twotable) {
            onetable onetable = (onetable) object[0];
            twotable twotable = (twotable) object[1];
    
            // Check if the tid is unique
            if (uniqueTids.add(onetable.getTid())) {
                // This tid is unique, process the result
                TestBean test = new TestBean();
    
                // Add your code here to process the unique result
            }
        }
    }
    

    In this code, we use a Set called uniqueTids to keep track of unique "tid" values. Before processing each result, we check if the "tid" is already in the set using uniqueTids.add(onetable.getTid()). If it's a new "tid," we process the result. This ensures that only unique "tid" values are processed, giving you a distinct result set based on "tid."