How to count the same value occurences in arrayList - java

Here is the snippet of code where I want to find the multiple occurrences of animal name.
I have written the code comparing the list indexes, but unable understand how to compare the names and count the number of occurrences of each name.
List<Animals> animalList= new ArrayList<Animals>();
try {
CallableStatement stmt = conn.prepareCall(callProcedure, ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
boolean results = stmt.execute();
if (results) {
ResultSet rs = stmt.getResultSet();
int count = 0;
while (rs.next()) {
Animals animal = new Animals();
animal.setAnimalName(rs.getString("animal_name"));
animal.setAge(rs.getString("age"));
animal.setHealth(rs.getString("health"));
animalList.add(animal);
count++;
}
}
int nbOccurences = 1;
for (int i = 0, length = animalList.size(); i < length; i++) {
if (i < length - 1) {
if (animalList.get(i) == animalList.get(i+1)) {
nbOccurences++;
}
} else {
System.out.println( animalList.get(i) + " occurs " + nbOccurences
+ " time(s)"); //end of array
}
if (i < length - 1 && animalList.get(i) != animalList.get(i+1)) {
System.out.println( animalList.get(i) + " occurs " + nbOccurences
+ " time(s)"); //moving to new element in array
nbOccurences = i;
}
}
} catch (SQLException sqlE) {
sqlE.printStackTrace();
}
return animalList;

The easiest solution, IMHO would be to stream the animal list, group by the name and count:
Map<String, Long> nameCount =
animalList.stream()
.collect(Collectors.groupingBy(Animal::getName,
Collectors.counting()));

Related

Save a Resultset to an Array in java

I want to save the result of a whole Mysql table in an array
String sDriver = "com.mysql.jdbc.Driver";
String sURL = "jdbc:mysql://www.odorxd.xyz:3306/u218933149_odor_base";
try {
Class.forName(sDriver).newInstance();
Connection con = DriverManager.getConnection(sURL, "u218933149_estenoesodor", "Tsunayoshi27?");
PreparedStatement stmt = null;
ResultSet rs = null;
stmt = con.prepareStatement("SELECT * FROM justname");
rs = stmt.executeQuery();
while (rs.next()) {
for (int x = 1; x <= rs.getMetaData().getColumnCount(); x++) {
System.out.print(rs.getString(x) + "\t");
}
System.out.println("");
}
} catch (SQLException sqle) {
sqle.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
it returns this to me from the database
run:
brandon
Brandon
Julio
Daniel
BUILD SUCCESSFUL (total time: 1 second)
I want to save what is in the database in an array to be able to implement it with a sort and search method
String str[] = { "Ajeet", "Steve", "Rick", "Becky", "Mohan", "Brandon", "Brandon Jesus", "Brandon Flores", "Brandon Flores Flores"};
String temp;
System.out.println("Strings in sorted order:");
for (int j = 0; j < str.length; j++) {
for (int i = j + 1; i < str.length; i++) {
// comparing adjacent strings
if (str[i].compareTo(str[j]) < 0) {
temp = str[j];
str[j] = str[i];
str[i] = temp;
}
}
System.out.println(str[j]);
}
that's why I need to save it in an array
I would appreciate any criticism or help as you do not have an idea, thank you
You can use a List.
List<String> list = new ArrayList<>();
while (rs.next()) {
for (int x = 1; x <= rs.getMetaData().getColumnCount(); x++) {
String str = rs.getString(x)
list.add(str);
System.out.print(str + "\t");
}
System.out.println();
}
String[] arr = list.toArray(new String[0]);
String temp;
// ... sort

Ideas to optimize this data comparison from base to base?

I wrote a little java (jdk1.8) class to compare data between two databases : one request get rows from source DB, then multitasks search each row in target DB (each thread get its own connection and preparedstatement).
The code below is ok (I just remove some logs, passwords, and some catch exceptions), for example I compare 28.700.000 rows, for a table with 140 columns, from DB2 to same table in Oracle, in 3 hours. Not incredible, but correct, I think ;).
So if you have some ideas to optimize this code, I take ideas :)
public class CompareDB {
public static AtomicInteger nbRowEqual = new AtomicInteger();
public static AtomicInteger nbRowNotFound = new AtomicInteger();
public static AtomicInteger nbRowDiff = new AtomicInteger();
public static AtomicInteger nbRowErr = new AtomicInteger();
public static List<PreparedStatement> targetPstmtPool = new ArrayList<PreparedStatement>();
public static final String[] columns = {"id", "col1", "col2", "col3", "col4"};
#SuppressWarnings({ "unchecked", "rawtypes" })
public static void main(String[] args) throws Exception {
int MAX_THREAD = 200, position = 0;
Integer targetPstmtNumber;
List<Connection> targetConnectionPool = new ArrayList<Connection>();
long beginExecTime = System.currentTimeMillis(), startReqTime;
DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss.SSS");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
// Create connection + preparedStatement pools to target DB
System.out.println("Start opening connections");
for (int i=0; i<MAX_THREAD; i++) {
Connection targetConn = DriverManager.getConnection("jdbc:oracle:thin:#<host>:<port>:<dbname>", "<user>", "<password>");
targetConn.setAutoCommit(false);
targetConn.setReadOnly(true);
targetConnectionPool.add(targetConn);
PreparedStatement targetPstmt = targetConn.prepareStatement("select "+String.join(",", columns)+" from mytable where id=?");
targetPstmtPool.add(targetPstmt);
}
// Connect + select from source DB
Connection sourceConn = DriverManager.getConnection("jdbc:db2://<IP>:<port>/<dbname>", "<user>", "<password>");
sourceConn.setAutoCommit(false);
sourceConn.setReadOnly(true);
Statement sourceStmt = sourceConn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet sourceResult = sourceStmt.executeQuery("select "+String.join(",", columns)+ " from owner.mytable");
System.out.println("Connections and statements opened in "+(System.currentTimeMillis()-beginExecTime)+" ms");
// Open pool of threads
ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 20, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue());
CompletionService<Integer> completion = new ExecutorCompletionService<Integer>(executor);
System.out.println("------------------------------------------------------------");
System.out.println("Start compare data ("+MAX_THREAD+" parallel threads)");
System.out.println();
startReqTime = System.currentTimeMillis();
// For each row of the source request
while (sourceResult.next()) {
// Set which pstmt to give to thread
if (position < MAX_THREAD) targetPstmtNumber = new Integer(position);
else targetPstmtNumber = completion.take().get();
// extract values from resultSet as parameter for next thread
List<Object> sourceRow = new ArrayList<Object>();
for (int i=1; i<=columns.length; i++) {
sourceRow.add(sourceResult.getObject(i));
}
// Call thread
completion.submit(new CompareDbThread(sourceRow, targetPstmtNumber));
position++;
if (position % 10000 == 0) System.out.println(" -- "+position+" rows --");
else if (position % 100 == 0) System.out.print(".");
}
// Await for last threads
System.out.println();
System.out.println("Waiting last threads...");
executor.awaitTermination(5, TimeUnit.SECONDS);
executor.shutdown();
// Close all Rs, Stmt, Conn
try {
System.out.println("------------------------------------------------------------");
System.out.println("Close all requests, statements, connections");
for (PreparedStatement targetPstmt : targetPstmtPool) targetPstmt.close();
for (Connection targetConn : targetConnectionPool) targetConn.close();
sourceResult.close();
sourceStmt.close();
sourceConn.close();
} catch (Exception e) {
System.out.println("[INFO] Error closing connections and requests : "+e.getMessage());
}
System.out.println("------------------------------------------------------------");
System.out.println("Data comparison done in "+(dateFormat.format(new Date(System.currentTimeMillis()-startReqTime)))
+" : "+nbRowEqual+" equals, "+nbRowNotFound+" not found, "+nbRowDiff+" diff, "+nbRowErr+" ERROR rows");
System.out.println("Threads : getCompletedTaskCount() = "+executor.getCompletedTaskCount()+", getTaskCount() = "+executor.getTaskCount());
System.out.println("Total time : "+(dateFormat.format(new Date(System.currentTimeMillis()-beginExecTime))));
}
}
public class CompareDbThread implements Callable<Integer> {
protected List<Object> sourceRow;
protected Integer targetPstmtNumber;
public CompareDbThread(List<Object> sourceRow, Integer targetPstmtNumber) {
this.sourceRow = sourceRow;
this.targetPstmtNumber = targetPstmtNumber;
}
public Integer call() {
ResultSet targetResult;
Object sourceColumnValue, targetColumnValue;
String sSourceColumnValue, sTargetColumnValue;
Double dSourceColumnValue, dTargetColumnValue;
boolean equalRow=true, equalColumn=true;
String message="", tempMessage="";
try {
PreparedStatement targetPstmt = CompareDB.targetPstmtPool.get(targetPstmtNumber.intValue());
targetPstmt.setObject(1, sourceRow.get(0));
targetResult = targetPstmt.executeQuery();
if (targetResult.next()) {
// Compare each column
for (int i=0; i<CompareDB.columns.length; i++) {
sourceColumnValue = sourceRow.get(i);
targetColumnValue = targetResult.getObject(i+1);
if ((sourceColumnValue!=null && targetColumnValue==null) || (sourceColumnValue==null && targetColumnValue!=null)) {
equalRow=false;
message += CompareDB.columns[i] + " : " + targetColumnValue + "(au lieu de " + sourceColumnValue + "), ";
}
else if (sourceColumnValue!=null && targetColumnValue!=null) {
// Compare as objects ...
if (!sourceColumnValue.equals(targetColumnValue)) {
sSourceColumnValue=sourceColumnValue.toString();
sTargetColumnValue=targetColumnValue.toString();
// if differents, compare as string ...
if (!sSourceColumnValue.equals(sTargetColumnValue)) {
tempMessage = CompareDB.columns[i] + " [String] : " + sTargetColumnValue + "(instead of " + sSourceColumnValue + "), ";
// if differents as string, compare as double
try {
dSourceColumnValue = new Double(sSourceColumnValue);
dTargetColumnValue = new Double(sTargetColumnValue);
if (!dSourceColumnValue.equals(dTargetColumnValue)) {
tempMessage = CompareDB.columns[i] + " [Number] : " + dTargetColumnValue + "(instead of " + dSourceColumnValue + "), ";
equalColumn=false;
}
}
catch (NumberFormatException e) {
equalColumn=false;
}
}
}
if (!equalColumn) {
message += tempMessage;
tempMessage = "";
equalColumn=true;
equalRow=false;
}
}
}
if (equalRow) {
CompareDB.nbRowEqual.incrementAndGet();
}
else {
CompareDB.nbRowDiff.incrementAndGet();
System.out.println(" [DIFFERENT] ["+CompareDB.columns[CompareDB.ID_COLUMN_POS]+"="+sourceRow.get(CompareDB.ID_COLUMN_POS)+"] => "+message);
}
}
else {
CompareDB.nbRowNotFound.incrementAndGet();
System.out.println(" [NOT FOUND] ["+CompareDB.columns[CompareDB.ID_COLUMN_POS]+"="+sourceRow.get(CompareDB.ID_COLUMN_POS)+"]");
}
}
catch (Exception e) {
CompareDB.nbRowErr.incrementAndGet();
System.err.println("[ERROR] "+CompareDB.columns[CompareDB.ID_COLUMN_POS]+"="+sourceRow.get(CompareDB.ID_COLUMN_POS)+" : "+e.getMessage());
}
return targetPstmtNumber;
}
}

2D object giving a nullpointerexception?

I'm having a bit of a problem when running the code below. This code is used when a button on a gui screen is pressed. Basically the function of this button is to read text entered into 2 text fields, derive a third value from the 2, and save all 3 in a row in a table on the GUI screen, using a 2d array.
However, i get a NullPointerException when executing it at the 5th line inside the method addItem().
saleData is the 2D array with data which is in the table.
i have instantiated the temp[][] object with 1 row more than the saleData object because i need to add a row to the table, and then i make saleData=temp.
This code worked as it is in the Gui class before i tried using OOP to create a separate class for the GUI to work from.
The nullpointer exception refers to the temp object, i know this because i printed out the value of temp and it was a null.
Does anyone have any ideas?
thanks in advance.
public void addItem() {
int len = saleData.length + 1;
Object[][] temp = new Object[len][3];
for (int k = 0; k < saleData.length; k++) {
for (int i = 0; i < 3; i++) {
temp[k][i] = ((DefaultTableModel) table.getModel()).getValueAt(k, i);
}
}
tblContainer.removeComponent(table);
try {
int qty = Integer.parseInt(txtQty.getText());
String item = (String) items.getSelectedItem();
String sql = "Select Sell_price from stockInfo where parts like '" + item + "'";
double total = 0;
if (saleData.length != 1) {
for (int i = 0; i < saleData.length; i++) {
String sql2 = "Select sell_price from stockinfo where parts like '" + temp[i][1].toString() + "'";
try {
System.out.println("Check 0");
pst = conn.prepareStatement(sql2);
System.out.println("Check 1");
rs = pst.executeQuery();
System.out.println("Check 2");
while (rs.next()) {
System.out.println("Check 3");
String qt = temp[i][0].toString();
temp[i][2] = Double.parseDouble(rs.getString("sell_price")) * Integer.parseInt(qt);
System.out.println("Check 4");
}
} catch (Exception e) {
Dialog.show("Error", "Error 1: " + e, "OK", null);
}
}
}
try {
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
while (rs.next()) {
double price = Double.parseDouble(rs.getString("Sell_Price"));
total = qty * price;
try {
for (int m = 0; m < saleData.length; m++) {
for (int n = 0; n < 3; n++) {
((DefaultTableModel) table.getModel()).setValueAt(m, n, temp[m][n]);
}
}
temp[saleData.length][0] = qty;
temp[saleData.length][1] = item;
temp[saleData.length][2] = total;
saleData = temp;
table = new Table(new DefaultTableModel(saleColumns, saleData, true));
tblContainer.addComponent(table);
((TableLayout) table.getLayout()).setGrowHorizontally(true);
saleForm.revalidate();
} catch (NullPointerException e) {
}
}
} catch (SQLException e) {
Dialog.show("Error", "SQL Error Record Sale", "OK", null);
}
} catch (NumberFormatException nfe) {
Dialog.show("Error", "Please enter a valid quantity", "OK", null);
}
}
The temp array can not be null. You just created it.
temp[k][i] can be null (and should be, by the way), but that does not matter - it is being assigned a value.
If a dimension of temp would not be big enough, you'd get an ArrayIndexOutOfBoundsException
So this leaves for two things that can get to be null (if the error stems from that line, and not for example from the inside of getValueAt(k,i) ):
table
table.getModel()
Use a debugger, and it will make your life easier...

Resultset getmethod in If condition

I'm working on java JDK7 and Microsoft Access 2007.Basically I want to get the minimum value from the all the columns of row1. But the following code doesn't work.
import java.io.*;
import java.util.*;
import java.net.*;
import java.sql.*;
public class server
{
public void check()
{
int min = 100, row = 0, index, i = 2;
try {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection cn = DriverManager.getConnection("jdbc:odbc:DSN2");
Statement st = cn.createStatement();
ResultSet rs = st.executeQuery("select *from Table1");
rs.next();
System.out.println(rs.getInt(1) + "\t" + rs.getInt(2) + "\t" + rs.getInt(3) + "\t" + rs.getInt(4) + "\t" + rs.getInt(5) + "\t" + rs.getInt(6));
for (i = 2; i < 7; i++)
{
System.out.println("hello");
if (rs.getInt(i) < min) {
index = i;
min = rs.getInt(i);
}
}
} catch (Exception e) {
e.getMessage();
}
switch (i) {
case 2:
ioConnect();
break;
case 3:
break;
case 4:
ioConnect();
break;
case 5:
ioConnect();
break;
case 6:
ioConnect();
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void ioConnect() {
try {
ServerSocket ss = new ServerSocket(2000);
Socket so = ss.accept();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter the message");
String str = br.readLine();
PrintStream ps = new PrintStream(so.getOutputStream());
ps.println(str);
} catch (Exception e) {
e.getMessage();
}
}
}
class serverm {
public static void main(String s[]) {
servern obj = new servern();
obj.check();
}
}
So here I get the output the first row each column values that's fine, but when the control enters the for loop the println statement prints the hello only once and the cursor blinks. This indicates the the program has not ended correctly.
Your first problem is that you don't know what your problem is...
To solve this problem, and get to solve the real issue, instead of this
catch(Exception e)
{
e.getMessage();
}
Use
catch(Exception e)
{
e.printStackTrace();
}
And please paste the full stack trace this produces...
EDIT
As OP stated in a comment:
there is no data found exception thrown
This means that there is no data to be read. Which is a known case for MS Access:
This typically occurs when you try to read the value of a column multiple times.
So you should only read every value once! To fix the imediate issue, comment the System.out.println() line here
...
rs.next();
// comment this:
// System.out.println(rs.getInt(1) + "\t" + rs.getInt(2) + "\t" + rs.getInt(3) + "\t" + rs.getInt(4) + "\t" + rs.getInt(5) + "\t" + rs.getInt(6));
for (i = 2; i < 7; i++)
...
And be careful, as you call getInt() for the same index two times in the loop, which has to be corrected:
for (i = 2; i < 7; i++)
{
System.out.println("hello");
if (rs.getInt(i) < min) { // getInt()
index = i;
min = rs.getInt(i); // second getInt() call for same index --- throws exception
}
}
Correct:
for (i = 2; i < 7; i++)
{
System.out.println("hello");
int value=rs.getInt(i); // getInt() call, put into local variable
if (value < min) {
index = i;
min = value; //just use local variable - OK
}
}
It is a small mistake that you have done. Irrespective of whether the result has record or not, you are calling rs.getInt(1)... . Use classical JDBC way of testing whether result set has records or not.
while(rs.next()){
rs.getInt(1);
}

Resultset to array and return with method

This is my code for database class method to get data in resultset and return an general array in this I have only one field in database.
Problem : I am not able to get the array abc[] and its contents and when I return it also says arrayIndexoutOfBond error "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 1
public String[] getTableContents(String tableName) {
ResultSet results = null;
String[] abc = null;
int a = 0;
try {
System.out.println(conn);
stmt = conn.createStatement();
results = stmt.executeQuery("select * from " + tableName);
ResultSetMetaData rsmd = results.getMetaData();
// int numberCols = rsmd.getColumnCount();
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
// print Column Names
System.out.print(rsmd.getColumnLabel(i) + "\t\t");
}
System.out.println("\n----------------------------------------");
while (results.next()) {
System.out.println(results.getString(2) + " 1");
String em = (results.getString(2));
System.out.println(em + " 2");
abc = em.split(" ");
System.out.println(abc + " 3");
}
results.close();
stmt.close();
} catch (SQLException suresh) {
System.out.println(suresh);
}
System.out.println(abc + " 4");
return abc;
}

Categories