Java ArrayList: Get Distinct Values from ArrayList which contain HashMap
Please see problem defination as describe below. I have ArrayList which cont开发者_JS百科ain HashMap. In HashMap one or many key-value pairs exist. ArrayList contain following:
HashMap1 contains key: column1 value:0001 key: column2 value:1 key: column3 value:1
HashMap2 contains key: column1 value:0001 key: column2 value:1 key: column3 value:2
Both HashMap1 and HashMap2 are kept inside ArrayList.
Now I enter a String like (column1, column2) Then I need output like Create new ArrayList containing following data:
HashMap1 contains key: column1 value:0001 key: column2 value:1
When I enter String like (column1, column3) Create new ArrayList containing following data:
HashMap1 contains key: column1 value:0001 key: column3 value:1
HashMap2 contains key: column1 value:0001 key: column3 value:2
i.e. I want to get distinct values from ArrayList according to Input String. Please Help me Logically as How can I achieve the same.
WHat you can do is;
for each map in the list.
copy the map.
map.keySet().retainAll(keys-you-want-to-keep)
set-of-results.add(map)
This way you will have the set of sub maps.
Nothing is more strict than code. So here is the to do what you want. Take a special look at the method selectColumns. The list of Maps is stored on the class field list.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Matrix {
private List<Map<String, String>> list = new ArrayList<Map<String,String>>();
public Matrix(int numRows) {
for (int i = 0; i < numRows; i++) {
list.add(new HashMap<String, String>());
}
}
private void set(int row, String string, String string2) {
list.get(row).put(string, string2);
}
public Matrix selectColumns(String... columns) {
Matrix select = new Matrix(list.size());
for (String column : columns) {
for (int row = 0; row < list.size(); row++) {
select.set(row, column, list.get(row).get(column));
}
}
return select;
}
public static Matrix createDummy(int dim) {
Matrix matrix = new Matrix(dim);
for (int i = 0; i < dim; i++) {
for (int j = 0; j < dim; j++) {
matrix.set(i, "col" + j, "val:" + i + "|" + j);
}
}
return matrix;
}
public static void main(String[] args) {
Matrix mainMatrix = Matrix.createDummy(3);
System.out.println(mainMatrix.list);
System.out.println(mainMatrix.selectColumns("col1", "col2").list);
}
}
精彩评论