简体   繁体   中英

How to extract unique fields from an ArrayList of objects?

Okay, I have been banging my head for this question. I feel the solution may be simple but I'm confused. Here goes:

I have an ArrayList of objects of type DbConnection . Each DbConnection object has the fields- DbName, SchemaName, AppId, Host, OsUser

Eg. sample rows:

Database Schema ApplId Host OsUser


EGPRD SYSTEM AAA dh7y7hdu oracle
EGPRD SYSTEM AAA d6f7d6fd linux
EGPRD ADM RDA d6f7d6fd linux
SOPRD DBLINK ACT fdf7f87e8 oracle

This ArrayList can have around 1000 objects like the above according to the application. Now, from this ArrayList, I want to extract those rows which are of a particular app id / database / schema combination and write this to a table in the database (table has fields database, schema, applId). It should extract that information from the arraylist and save in the table.

So this table will look like this when unique rows are inserted:

Request Id Database Schema ApplId


1234 EGPRD SYSTEM AAA
1234 EGPRD ADM RDA
1234 SOPRD DBLINK ACT

1234 is the request id that has been generated when all the 1000 rows were updated in some other table.

How do I pick out unique combination of values from an arraylist of objects? I mean each object has many fields (db, schema, appid, host, osuser) but I need only three combinations (db, schema, appid), so unique combinations will be inserted in the database table.

If you want to extract unique fields, you need to create a function that goes through your list , item by item, and checks if there are any item that are 'equal' to the one you're currently on.

(You also need to skip the one on the same index of the list)

for (i = 0; i < list.size(); ++i) {
    for (j = 0; i < list.size(); ++j) { 
        if (list[i] == list[j] && i != j) {
            // Do your stuff here.
        }
    }
}

You could overload the '==' operator if this is a custom class, or you could simply check one attribute like the name, etc.

if (list[i].requestID == list[j].requestID && i != j) { ...

Here is your DbConnection class. You have to overwrite the equal method to check each element is equal or not. DbConnection.java

public class DbConnection {

    private String DbName;
    private String SchemaName;
    private String ApplId;
    private String Host;
    private String OsUser;

    public DbConnection(String DbName, String SchemaName, String ApplId, String Host, String OsUser) {
        this.DbName = DbName;
        this.SchemaName = SchemaName;
        this.ApplId = ApplId;
        this.Host = Host;
        this.OsUser = OsUser;
    }

    public String getDbName() {
        return DbName;
    }

    public String getSchemaName() {
        return SchemaName;
    }

    public String getApplId() {
        return ApplId;
    }

    public String getHost() {
        return Host;
    }

    public String getOsUser() {
        return OsUser;
    }

    @Override
    public boolean equals(Object obj) {

        if (obj instanceof DbConnection) {
            DbConnection dbConnection = (DbConnection) obj;

            if (this.ApplId.equals(dbConnection.getApplId()) && 
                    this.DbName.equals(dbConnection.getDbName()) && 
                    this.SchemaName.equals(dbConnection.getSchemaName())) {
                return true;
            }
        }

        return false;

    }

}

Main Mathod: First insert all element to array list and Make another arraylist where you store all of your unique element. Then iterate your first list and check first list's already exist or not in unique list. If not exist then add this item to unique list.

public static void main(String[] args) throws IOException {

    ArrayList<DbConnection> arrayList = new ArrayList<>();
    arrayList.add(new DbConnection("EGPRD", "SYSTEM", "AAA", "dh7y7hdu", "oracle"));
    arrayList.add(new DbConnection("EGPRD", "SYSTEM", "AAA", "d6f7d6fd", "linux"));
    arrayList.add(new DbConnection("EGPRD", "ADM", "RDA", "dh7y7hdu", "linux"));
    arrayList.add(new DbConnection("SOPRD", "DBLINK", "ACT", "fdf7f87e8", "oracle"));

    ArrayList<DbConnection> newList = new ArrayList<>();
    for (DbConnection dbConnection : arrayList) {

        if (newList.isEmpty()) {
            newList.add(dbConnection);
        } else {

            boolean existenceStatus = false;

            for (DbConnection newSingleElement : newList) {
                if (newSingleElement.equals(dbConnection)) {
                    existenceStatus = true;
                    break;
                }
            }

            if(!existenceStatus) {
                newList.add(dbConnection);
            }
        }

    }

    for (DbConnection dbConnection : newList) {
        System.out.println(dbConnection.getDbName() + " : "
                + dbConnection.getSchemaName() + " : "
                + dbConnection.getApplId() + " : ");
    }
}

I think you will like this...

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class Exam {
    public static void main(String[] args) {
        DbConnection dc1 = new DbConnection("EGPRD","SYSTEM","AAA","dh7y7hdu", "oracle");
        DbConnection dc2 = new DbConnection("EGPRD","SYSTEM","AAA","d6f7d6fd", "linux");
        DbConnection dc3 = new DbConnection("EGPRD","ADM","RDA","d6f7d6fd", "linux");
        DbConnection dc4 = new DbConnection("SOPRD","DBLINK","ACT","fdf7f87e8", "oracle");

        List<DbConnection> dcList = new ArrayList(4);
        dcList.add(dc1);
        dcList.add(dc2);
        dcList.add(dc3);
        dcList.add(dc4);

        Map uniqueTable = new Hashtable();
        for( DbConnection fDc : dcList ){
            uniqueTable.put(fDc.key, fDc);
        }

        for( Iterator it = uniqueTable.keySet().iterator();it.hasNext(); ){
            DbConnection mDc = (DbConnection)uniqueTable.get(it.next());
            System.out.println( "1234" + "\t"+ mDc.DbName + "\t" + mDc.SchemaName + "\t" + mDc.AppId);
        }
    }
}

class DbConnection{

    public DbConnection(String dbName, String schemaName, String appId, String host, String osUser) {
        super();
        DbName = dbName;
        SchemaName = schemaName;
        AppId = appId;
        Host = host;
        OsUser = osUser;
        key = DbName + SchemaName + AppId; // key generation 
    }
    public String key;
    public String DbName;
    public String SchemaName;
    public String AppId;
    public String Host;
    public String OsUser;
}

If you can not modify a Db Connection guess you could use the inherited or wrappers.

class DbConnectionEx extends DbConnection{
    public String key;
    public DbConnectionEx(String dbName, String schemaName, String appId, String host, String osUser) {
        super(dbName, schemaName, appId, host, osUser);
        key = DbName + SchemaName + AppId; // key generation 
    }   
}

You can use TreeSet to remove doublets, pseudocode:

TreeSet<DbConnection> set= new TreeSet<>((l, m) -> (l.getSchema() +l.getDababase()...).compareTo(m.getSchema() + l.getDatabase()+ ...));
for (DbConnection item : list) {
    if (/*condition*/) {
        set.add(item);
    }
}
for (DbConnection item : set) {
      //add to db
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM