Compare two Lists and same values store in third List issue

user8616404 :

Hy, I am having trouble with comparing two list. The goal is to compare two lists, find the same values and store those values into third list. What I have found till yet is just the way to return boolean value, but no way to return list value.. any ideas?

here are my two methods for getting values from database:

@Override
public List<BrojPolice> dohvatiBrojPolice() {
    List<BrojPolice> filter = jdbcTemplate.query("SELECT*FROM ins2.kalk_cpi;",new Object[]{},
            (rs,rowNum) ->{
                BrojPolice bp = new BrojPolice();
                bp.setBroj(rs.getString("BROJ_POLICE"));
                return bp;
            });
    return filter;
}


@Override
public List<BrojPolice> dohvatiBrojPolice2() {
    List<BrojPolice> filter2 = jdbcTemplate.query("SELECT*FROM ins_RAZNO.ADND_DATOTEKA;",new Object[]{},
            (rs,rowNum) ->{
                BrojPolice bp = new BrojPolice();
                bp.setBroj(rs.getString("BROJ_POLICE"));
                return bp;
            });
    return filter2;
}

public List<String> brojPolice(){
    boolean match = dohvatiBrojPolice().contains(dohvatiBrojPolice2());

     //ideas?

    return //List
}
Naman :

You can use List.retainAll as :

List<BrojPolice> common = new ArrayList<>(dohvatiBrojPolice());
common.retainAll(dohvatiBrojPolice2());

This would require the BrojPolice to be comparable with proper hashCode and equals.

If you're looking for a stream or forEach solution for this

List<BrojPolice> common = dohvatiBrojPolice().stream()
                                     .filter(a -> dohvatiBrojPolice2().contains(a))
                                     .collect(Collectors.toList());

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=130838&siteId=1