'Update element of LinkedHashSet which is a collection
I have a nested collection structure representing Schema, Table, Column
public class SSchema{
private String schemaName;
private LinkedHashSet<STable> tableSet;
}
public class STable {
private String tableFullName;
private String tableDisplayName;
private LinkedHashSet<SColumn> columnSet;
}
public class SColumn {
private String columnFullName;
private String columnDisplayName;
private String columnType;
}
I retrieve the list of columns from an API and populate a LinkedHashSet of columns, I then get the Tables these columns belong to and am trying to update the LinkedHashSet of Columns inside each Table. Unfortunately, there is no API to get the columns for a table in this API
LinkedHashSet<SColumn> sColumnSet = getSColumnsFromAPI();
LinkedHashSet<STable> sTableSet = getSTablesForColumns(sColumnSet);
In the function getSTablesForColumns,
private LinkedHashSet<STable> getSTablesForColumns(LinkedHashSet<SColumn> sColumnSet) throws IOException,JsonParseException {
sTableSet = new LinkedHashSet<STable>();
sColumnSet.forEach(sColumn -> {
String[] tablesList = getTablesFromApi(sColumn) //get the tables this column is in
foreach(String tableName:tablesList){
STable table = STable.builder()
.tableFullName(tableName)
.build();
//This is where the problem is - need a way to get the existing table
if(sTableSet.contains(table){
// get existing table from sTableSet - how do I do this?
existingTable.getColumnSet().add(stiboColumn);
}
else { //new table, not in collection
LinkedHashSet<SColumn> columnSet = new LinkedHashSet<SColumn>();
columnSet.add(sColumn);
table.setColumnSet(columnSet);
sTableSet.add(table);
};
}
});
return sTableSet;
}
The question/difficulty I am having is: How do I efficiently find the existing sTable in the LinkedHashSet and update the LinkedHashSet inside this sTable with the additional sColumn?
Edit: I came up with the following fix before the much better solution below:
My earlier solution was to check if the table existed in the collection (I had moved the sTableSet to a class variable):
boolean existingTable=false;
for(STable sTable : sTableSet){
String collectionSTableName = sTable.getTableFullName();
if (collectionSTableName.equals(table)){
existingTable=true;
sTable.getColumnSet().add(sColumn);
break;
}
}
if(existingTable==false) { //new table, not in collection
LinkedHashSet<SColumn> columnSet = new LinkedHashSet<SColumn>();
columnSet.add(sColumn);
table.setColumnSet(columnSet);
sTableSet.add(table);
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
