Map.clear() then add map to List - java

I try to traverse some excel2007 data by using poi.jar based on jdk1.6.But when I seem to find a strange phenomenon that when I traverse the row(stored by HashMap()) and then add the row data to java.util.ArrayList .
And starting the next iterator,I first clear the row data by invoking Map.clear(), but when again invoking the ArrayList.add() method,this row data is overridden the older data.
Map<String, String> cellForRow = = new HashMap<String, String>();
List<Map<String, String>> rowForSheet = new ArrayList<Map<String, String>>();
for (int j = 0; j < sheet.getPhysicalNumberOfRows(); j++) {
row = sheet.getRow(j);
if (j == 0) {// the first row is title
titleRow = row;
continue;
}
if (row != null && titleRow.getPhysicalNumberOfCells() > 0) {
// cellForRow = new HashMap<String, String>();
cellForRow.clear();
for (int k = 0; k < titleRow.getPhysicalNumberOfCells(); k++) {// cell
cellForRow.put(getCellValue(titleRow.getCell(k)), getCellValue(row.getCell(k)));
}
}
rowForSheet.add(cellForRow);
}
Next Snippets show the debug log for rowForSheet(List)
[{ Up =Stream, Email=XXX,Down =Stream},
{ Up =Stream, Email=XXX,Down =Stream},
{ Up =Stream, Email=XXX,Down =Stream},
{ Up =Stream, Email=XXX,Down =Stream},
{ Up =Stream, Email=XXX,Down =Stream}]
the later data override the older data
Did you?

First off, I would put the creation of your map inside of the loops so you add a new map each time.
List<Map<String, String>> rowForSheet = new ArrayList<Map<String, String>>();
for (int j = 0; j < sheet.getPhysicalNumberOfRows(); j++) {
row = sheet.getRow(j);
if (j == 0) {// the first row is title
titleRow = row;
continue;
}
Map<String, String> cellForRow = = new HashMap<String, String>();
if (row != null && titleRow.getPhysicalNumberOfCells() > 0) {
for (int k = 0; k < titleRow.getPhysicalNumberOfCells(); k++) {// cell
cellForRow.put(
getCellValue(titleRow.getCell(k)),
getCellValue(row.getCell(k))
);
}
}
rowForSheet.add(cellForRow);
}
Now each item in the list will be a different map, with the new data you've added.

Related

java.lang.UnsupportedOperationException: null

I am trying to delete empty cell in apache-poi. I get this error at
unmarkedColumns.remove(unmarkedColumns.get(i)):
There is a problem with remove method.
I don't understand why.Can you help me?
java.lang.UnsupportedOperationException: null
at java.util.AbstractList.remove(Unknown Source)
at java.util.AbstractList$Itr.remove(Unknown Source)
)
Integer[] integers = new Integer[headers.size()];
Arrays.fill(integers, 0);
List<Integer> unmarkedColumns = Arrays.asList(integers);
for (ScoredFormData scoredFormData : scoredFormDatas) {
Row dataRow = sheet.createRow(++rownum);
List<Object> rowValues = prepareExportRow(scoredFormData, visitManager, parameters,
dynamicDatamanager,
scoreCriteriaDefinitions);
for (int i = 0; i < rowValues.size(); i++) {
if (unmarkedColumns.get(i) != 1 && rowValues.get(i) != null
&& !rowValues.get(i).equals("")) {
unmarkedColumns.set(i, 1);
}
}
populateCells(rowValues, dataRow);
}
for (int i = 0; i < unmarkedColumns.size(); i++) {
if (unmarkedColumns.get(i) == 0) {
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
Boolean changed = false;
for (int j = i + 1; j < row.getLastCellNum() + 1; j++) {
Cell oldCell = row.getCell(j - 1);
if (oldCell != null) {
row.removeCell(oldCell);
changed = true;
Cell nextCell = row.getCell(j);
if (nextCell != null) {
Cell newCell = row.createCell(j - 1, nextCell.getCellType());
switch (newCell.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN: {
newCell.setCellValue(nextCell.getBooleanCellValue());
break;}}}}
if (changed ) {
unmarkedColumns.remove(unmarkedColumns.get(i));
i = 0;
}
}
Arrays.asList(..) returns a List with a fixed size, so you can't expand or shrink it.
To fix it, you could wrap it in an ArrayList:
List<Integer> unmarkedColumns = new ArrayList<>(Arrays.asList(integers));
Your problem is here
List<Integer> unmarkedColumns = Arrays.asList(integers);
If you use Arrays.asList(...), it returns a fixed size list, therefore you cannot remove elements from it.
You could make a workaround by wrapping it:
List<Integer> list = new ArrayList<Integer>(Arrays.asList(integers));

Displaying the string values of 2 dimensional Object array

I am trying to display the contents of an array after iterating through rows and columns of a JTable. I tried Arrays.toString(myTwoDimensionalArrayVariable) but it won't display the string values.
My goal is to check duplicates for every column per row of a destination JTable when user tries to add row values from a source JTable that's why I want to display the contents of the array.
The values on columns are combination of double, String, and int.
int myRowCount = aJTableParameter.getRowCount();
int myColumnCount = aJTableParameter.getColumnCount();
Object[][] myRowValues = new Object[myRowCount][myColumnCount];
for (int j = 0; j < myRowCount; j++) {
for(int i = 0; i< myColumnCount; i++){
myRowValues[j][i] = aDestinationTable.getValueAt(j, i);
}
}
System.out.println(Arrays.toString(myRowValues));
if (Arrays.asList(myRowValues).contains(column1Value)
&& Arrays.asList(myRowValues).contains(column2Value)
&& Arrays.asList(myRowValues).contains(column3Value)
&& Arrays.asList(myRowValues).contains(column4Value)) {
JOptionPane.showMessageDialog(null, "Duplicate, try again.");
}else{
//do something else
}
I only get this output:
run:
Successfully recorded login timestamp
[]
[[Ljava.lang.Object;#35fa3ff2]
[[Ljava.lang.Object;#407c448d, [Ljava.lang.Object;#1e78a60e]
Is there any other alternative than using 2 Dimensional Arrays?
I'd appreciate any help.
Thanks.
IFF your JTable cells contain only Strings, you can define your array as String[][] instead of Object[][] and fill it with your JTable contents using aDestinationTable.getValueAt(j, i).toString().
EDIT: since that's not the case (as per your comment), it's probably better to use a List, like this:
List<List<Object>> objectList = new ArrayList<>();
for (int j = 0; j < 2; j++) {
objectList.add(j, new ArrayList<>());
for (int i = 0; i < 2; i++) {
if (i==0) objectList.get(j).add("string" + j + i);
if (i==1) objectList.get(j).add((double) 37.8346 * j * i);
}
}
System.out.println("OBJECT LIST: "+objectList);
Output:
OBJECT LIST: [[string00, 0.0], [string10, 37.8346]]
Your code should look like this, then:
List<List<Object>> myRowValues = new ArrayList<>();
for (int j = 0; j < myRowCount; j++) {
myRowValues.add(j, new ArrayList<>());
for (int i = 0; i < myColumnCount; i++) {
myRowValues.get(j).add(aDestinationTable.getValueAt(j, i));
}
}
System.out.println(myRowValues);

Displaying duplicate results in arraylist java

I am using JDBC to run a SQL query in Java. I want to take the result of the query and store it in an arraylist so that I can display the data in a graph of some sort. I'm getting the same line printing out the same number of times as columnCount. Here is my code.
ArrayList <String[]> result = new ArrayList<String[]>();
int columnCount = rset.getMetaData().getColumnCount();
if(rset!=null)
{
while(rset.next())
{
found=true;
String[] row = new String[columnCount];
for (int i = 0; i < columnCount; i++) {
row[i] = rset.getString(i + 1);
row[i] = rset.getString("Date") + " "
+ rset.getString("Hour");
System.out.println(row[i]);
}
result.add(row);
}
Your second row[i] rewrites the value of the column. Just remove it and you'll see your records:
...
for (int i = 0; i < columnCount; i++) {
row[i] = rset.getString(i + 1);
}
System.out.println(Arrays.toString(row));
result.add(row);
...

Selection sort to merge sort

Below I have provided my example of selection sort code, which if possible I want to convert to merge sort (I am using a linked-list as my data type):
public void sortRawDataRepository() {
for (int i = 0; i < rawDataRepository.size(); i++) {
for (int j = i + 1; j < rawDataRepository.size(); j++) {
Date iDate = rawDataRepository.get(i).getProductionDate();
Date jDate = rawDataRepository.get(j).getProductionDate();
if (iDate.getTime() > jDate.getTime()) {
Item tmp = rawDataRepository.get(i);
rawDataRepository.set(i, rawDataRepository.get(j));
rawDataRepository.set(j, tmp);
}
}
}
}

Trying to use a Hashmap<Integer, Integer>

how would I increment the key [i] by 1 in this situation every time I run through this for loop with the way I currently have it set up all the elements only get mapped to 1. I am trying to find out how many times each number occurs. I have tried +1 in the empty spot after list.get(i) but again only maps each element to 1. thank you.
List<Integer> list = new ArrayList<Integer>();
HashMap<Integer,Integer> Mode = new HashMap<Integer, Integer>();
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
list.add(arr[i][j]);
}
}
System.out.println(list);
int count = 1;
for(int i = 0; i < list.size(); i ++) {
Mode.put(list.get(i), );
You need to specify a Key here.
for(int i = 0; i < list.size(); i++) {
int value=list.get(i);
if(!Mode.containsKey(value))
Mode.put(value,1);
else
Mode.put(value,Mode.get(value)+1);
}
According to your comment,
for(int i = 0; i < list.size(); i ++) {
if(Mode.containsKey(list.get(i)) ){
Integer count = Mode.get(list.get(i));
Mode.put(list.get(i), ++count);}
else
Mode.put(list.get(i), 1);
If you have the option, you may find it easier to use something like Multiset from Guava.
Multiset<Integer> seen = HashMultiset.create();
for (int[] row : arr) {
for (int elem : row) {
seen.add(elem); // none of that nasty dealing with the Map
}
}
// you can look up the count of an element with seen.count(elem)
E mostCommon = null;
int highestCount = 0;
for (Multiset.Entry<Integer> entry : seen.entrySet()) {
if (entry.getCount() > highestCount) {
mostCommon = entry.getElement();
highestCount = entry.getCount();
}
}
return mostCommon; // this is the most common element

Categories