Как я могу преобразовать SQL-запрос в лямбду или поток (Java 8)? - PullRequest
2 голосов
/ 20 мая 2019

Я начинаю в Java и хотел бы преобразовать запрос в SQL в Lambda или Stream в Java 8.

Следуйте приведенному ниже запросу.

SELECT * FROM Correspondencia c, (SELECT entidadeOrigem, MAX(m1) similaridadeMaxima FROM Correspondencia WHERE m1 <> 0 GROUP BY entidadeOrigem) r WHERE c.entidadeOrigem = r.entidadeOrigem AND c.m1 = 
r.similaridadeMaxima

Я создал Correpondenciaкласс с геттерами и сеттерами ниже:

public class Correspondencia {

    int codigo;
    String nome;
    String entidadeOrigem;
    String EntidadeDestino;
    double m1;
    double m2;
    double m3;


double medMax;
    double dem;


    public int getCodigo() {
        return codigo;
    }
    public void setCodigo(int codigo) {
        this.codigo = codigo;
    }
    public String getNome() {
        return nome;
    }
    public void setNome(String nome) {
        this.nome = nome;
    }
    public String getEntidadeOrigem() {
        return entidadeOrigem;
    }
    public void setEntidadeOrigem(String entidadeOrigem) {
        this.entidadeOrigem = entidadeOrigem;
    }
    public String getEntidadeDestino() {
        return EntidadeDestino;
    }
    public void setEntidadeDestino(String entidadeDestino) {
        EntidadeDestino = entidadeDestino;
    }
    public double getM1() {
        return m1;
    }
    public void setM1(double m1) {
        this.m1 = m1;
    }
    public double getM2() {
        return m2;
    }
    public void setM2(double m2) {
        this.m2 = m2;
    }
    public double getM3() {
        return m3;
    }
    public void setM3(double m3) {
        this.m3 = m3;
    }
    public double getMedMax() {
        return medMax;
    }
    public void setMedMax(double medMax) {
        this.medMax = medMax;
    }
    public double getDem() {
        return dem;
    }
    public void setDem(double dem) {
        this.dem = dem;
    }
}

Я создал список:

List<Correspondencia> cor = new ArrayList<Correspondencia>();

cor.add(new Correspondencia(41,"Paper_Organization","Paper", "Organization",0,0.14,0.04,0.23,0.08));
cor.add(new Correspondencia(22,"Paper_Organization","Paper", "Organization",0,0.15,0.04,0.23,0.08));
cor.add(new Correspondencia(22,"Paper_Organization","Paper", "Organization",0,0.36,0.04,0.23,0.08));
cor.add(new Correspondencia(11,"email_hasanemail","email", "hasanemail",0.19,0.21,0.19,0.,0.12));
cor.add(new Correspondencia(11,"email_hasanemail","email", "hasanemail",0.25,0.21,0.19,0.,0.12));
cor.add(new Correspondencia(11,"email_hasanemail","email", "hasanemail",0.37,0.21,0.19,0.,0.12));
cor.add(new Correspondencia(31,"Review_Reviewer","Review","Reviewer",0.36,0.5,0.41,0.,0.25));
cor.add(new Correspondencia(31,"Review_Reviewer","Review","Reviewer",0.38,0.5,0.41,0.,0.25));
cor.add(new Correspondencia(31,"Review_Reviewer","Review","Reviewer",0.37,0.5,0.41,0.,0.25));
cor.add(new Correspondencia(32,"email_hasanemail","email", "hasanemail",0.36,0.5,0.41,0.,0.25));
cor.add(new Correspondencia(01,"PaperAbstract_Abstract","PaperAbstract","Abstract", 0.33,0.45,0.32,0.,0.22));
cor.add(new Correspondencia(01,"PaperAbstract_Abstract","PaperAbstract","Abstract", 0.37,0.45,0.32,0.,0.22));

Теперь я хочу отфильтровать курс с помощью Lambda или Stream согласно следующему запросу:

SELECT * FROM Correspondencia c, (SELECT entidadeOrigem, MAX(m1) similaridadeMaxima FROM Correspondencia WHERE m1 <> 0 GROUP BY entidadeOrigem) r WHERE c.entidadeOrigem = r.entidadeOrigem AND c.m1 = r.similaridadeMaxima

, который в результате возвращает мне наибольшее значение m1, сгруппированное по элементам entidadeOrigem:

22,"Paper_Organization","Paper", "Organization",0,0.36,0.04,0.23,0.08
11,"email_hasanemail","email", "hasanemail",0.37,0.21,0.19,0.,0.12
31,"Review_Reviewer","Review","Reviewer",0.38,0.5,0.41,0.,0.25
01,"PaperAbstract_Abstract","PaperAbstract","Abstract", 0.37,0.45,0.32,0.,0.22

Коллега дал мне следующий код:

Correspondencia maxM1 = cor.stream()
            .filter(x -> x.getM1() != 0)
            .max(Comparator.comparing(x -> x.getM1()))
            .get();

        System.out.println(maxM1);

Однако он возвращает только наибольшее значение m1 entidadeOrigem.

И что мне нужно, это возвращение наибольшего значения для каждого повторяющегося элемента m1, сгруппированного по entidadeOrigem в соответствии с SQL ниже.

SELECT * FROM Correspondencia c, (SELECT entidadeOrigem, MAX(m1) 
similaridadeMaxima FROM Correspondencia WHERE m1 <> 0 GROUP BY 
entidadeOrigem) r WHERE c.entidadeOrigem = r.entidadeOrigem AND c.m1 = 
r.similaridadeMaxima

1 Ответ

1 голос
/ 20 мая 2019

Сначала выполните группировку на основе поля entidadeOrigem в Map<String,List<Correspondencia>>, из каждого списка получите максимальное значение

List<Correspondencia> result = cor.stream()
       .collect(Collectors.groupingBy(Correspondencia::getEntidadeOrigem))
       .values()
       .stream()
       .map(c->c.stream().max(Comparator.comparingDouble(Correspondencia::getM1)))
       .filter(p->p.isPresent())
       .map(Optional::get)
       .collect(Collectors.toList());
...