-4

I Have a query result with many fields, and i have to insert only unique rows in the collection based on the 3 columns of the table using java code.

Suppose query result is like below :

Col A | Col B | Col C | Col D| Col E

1 | 2 | 1 | V1 | A

1 | 2 | 1 | V2 | A

2 | 1 | 1 | V3 | B

3 | 2 | 2 | V4 | C

2 | 1 | 1 | V5 | B

Here for row 1 and 2 are duplicate as per combination of col A + Col B + Col C and row 3 and row 5 are also duplicate.

So i have to insert only unique values in the collection based on col A,col B and Col C

Result :Row 1,3,4 should be interested in the collection rest shouldn't. Please suggest me solution.

1 Answers1

1

You could create a POJO with 5 fields for each row and use a Set which doesn't allow duplicates. Have the POJOs implement equals and hashcode where you define what equals means.

Example:

public class Row {

    private Integer col1;
    private Integer col2;
    private Integer col3;
    private Integer Col4;
    private Integer Col5;

    public Row(Integer col1, Integer col2, Integer col3) {
        this.col1 = col1;
        this.col2 = col2;
        this.col3 = col3;
    }

    //gets sets

    public Integer getCol1() {
        return col1;
    }

    public Integer getCol2() {
        return col2;
    }

    public Integer getCol3() {
        return col3;
    }

    @Override
    public boolean equals(Object o) {
        if (o == null || !(o instanceof Row))
            return false;

        if (this == o)
            return true;

        Row other = (Row)o;
        if (col1.equals(other.getCol1()) && col2.equals(other.getCol2()) && col3.equals(other.getCol3())) {
            return true;
        }
        return false;
    }
    @Override
    public int hashCode() {
        return col1+col2+col3;
    }
}

Testing:

public static void main(String args[]){
    Main m = new Main();
    Row r1 = m.new Row(1,1,2);
    Row r2 = m.new Row(2,3,4);
    Row r3 = m.new Row(1,1,2);
    Row r4 = m.new Row(2,3,2);

    Set<Row> set = new HashSet<>();
    set.add(r1);
    set.add(r2);
    set.add(r3);
    set.add(r4);

    for (Row row : set) {
        System.out.println(row.getCol1() + ":" + row.getCol2() + ":" + row.getCol3());
    }
}
Jack Flamp
  • 1,223
  • 1
  • 16
  • 32