How to iterate column values in an object's list? - java

Here's my code:
public String generateEISReports_PDF(){
surveyReportService.setSurveyReportDA(surveyReportDA);
surveyReportList = surveyReportService.getSurveyReport(surveyType, surveyDate, projectCode, employeeCode);
if(surveyReportList != null){
System.out.println(surveyReportList + "testing");
System.out.println(surveyReportList.size() + "size ito");
for (SurveyReport surveyReport : surveyReportList) {
System.out.println(surveyReport.getRiskRank().toString() + "asdf");
surveyReports.add(surveyReport);
}
}
this.compileTheJasperReports();
return SUCCESS;
}
I am getting the whole row values with this code as an object. I want to iterate the field values in every list of objects. How can I do that?

By using reflection you can achieve that. Following is the code. This might help you.
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class SurveyReport {
public int localServeryCont; // if you make it private then changes have to be done in 'SurveyIterator' inner class.
public String surveyReporterName;
public static void main(String[] args) {
List<SurveyReport> surveyReportList = new ArrayList<SurveyReport>();
SurveyReport sr = new SurveyReport(); //first object creation
sr.localServeryCont = 10;
sr.surveyReporterName = "AAA";
surveyReportList.add(sr);
sr = new SurveyReport(); //second object creation
sr.localServeryCont = 100;
sr.surveyReporterName = "BBB";
surveyReportList.add(sr); //two objects are in the list-object.
for (SurveyReport surveyReport : surveyReportList) {
Iterator<String> itr = surveyReport.iterator(); //You can work around with 'java.lang.Iterable' to use 'foreach' loop
while (itr.hasNext()) { //this is what you might be expecting
System.out.println("SurveyReport's object's values : " + itr.next());
}
}
}
public Iterator<String> iterator() { //here is method to get iterator object.
return new SurveyIterator();
}
private class SurveyIterator implements Iterator<String> { //creating 'SurveyIterator' INNER class
private int totalAvailableField = SurveyReport.class.getDeclaredFields().length;
int cursor = 0;
Field[] surveyReportFields = SurveyReport.class.getFields();
#Override
public boolean hasNext() {
return cursor != totalAvailableField;
}
#Override
public String next() {
String next = null;
try {
next = (surveyReportFields[cursor].get(SurveyReport.this)).toString();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
cursor++;
return next;
}
#Override
public void remove() {
throw new UnsupportedOperationException();
}
}
}

Related

Sorting Arraylist with multiple data types by date (numeric)

This is what I have. Im scanning the txt and passing it to an array as a string (per line). I need to sort by date
package stocktest;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
/**
*/
public class StockTest {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
ArrayList aList = new ArrayList();
java.io.File file = new java.io.File("transactions.txt");
try {
Scanner input = new Scanner(file);
while (input.hasNext()) {
String data = input.nextLine();
aList.add(data);
System.out.println(aList);
}
} catch (FileNotFoundException e) {
System.err.format("File does not exist/n");
}
}
}
Each line in transaction.txt looks like this
buy,1/2/2002,IBM,30,135.00
I need to sort the list by date.
What do you think I should do?
Thanks in advance.
first of all why dont you try to parse each line by "," and put it to a class that will have a states and methods, by that you can use comparator to sort an array list see my example.
private List<OrderDTO> orderDTOs;
public class OrderDtoDateDescComparator implements Comparator<OrderDTO> {
#Override
public int compare(OrderDTO orderDTO, OrderDTO other) {
if (orderDTO.getDateCreated() != null && other.getDateCreated() != null) {
return orderDTO.getDateCreated().compareTo(other.getDateCreated());
} else if (orderDTO.getDateCreated() != null && other.getDateCreated() == null) {
return 1;
} else if (orderDTO.getDateCreated() == null && other.getDateCreated() != null) {
return -1;
}
return 0;
}
}
Collections.sort(this.orderDTOs, new OrderDtoDateDescComparator());
see now that will be easy. as it is.
This is a cool use case for a Comparator.
Collections.sort(aList, new Comparator<String>() {
public int compare(String s1, String s2) {
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yy");
try {
Date d1 = format.parse(s1.split(",")[1]);
Date d2 = format.parse(s2.split(",")[1]);
return d1.compareTo(d2);
} catch (ParseException e) {
// handle exception
}
}
});

Java Reflection/BeanUtils issue

I'm trying to populate a bean with some table driven attribute:value pairs. I retrieve them from a MySQL table, and populate a hashmap just fine. I iterate through the hashmap, and if I use PropertyUtils.setProperty() I get a "Class does not have setter for *" error. If I use BeanUtils.setProperty() the bean never gets populated. Here's the sample:
public class DBDrivenPayloadHandler extends GDE{
DbDrivenPayloadHandlerBean bean;
#SuppressWarnings("rawtypes")
public void populateBean() throws Exception {
ITransaction trans = new MySQLTransaction();
IAdapterDataMapDAO adapterDataMap = new MySQLAdapterDataMapDAO();
adapterDataMap.setTransaction(trans);
HashMap<String, String> values = adapterDataMap.getHashMap(super.getCurrentAccountId());
//hashmap gets populated correctly with correct variable names and values != "-1";
DbDrivenPayloadHandlerBean bean = new DbDrivenPayloadHandlerBean();
//We have a bean with all the intialized variable values
Iterator it = values.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry)it.next();
try {
PropertyUtils.setProperty(bean, (String) entry.getKey(), entry.getValue());
//PropertyUtils will give a setter not found error. BeanUtils never sets the values.
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void getInfo(String fileName) {
try {
populateBean();
} catch (Exception e) {
e.printStackTrace();
}
APPTS_FULLNAME_POS = bean.getAPPTS_FULLNAME_POS();
APPTS_DATETIME_POS = bean.getAPPTS_DATETIME_POS();
//Both still -1;
super.getInfo(filename);
}
And here's the Bean (or at least some of it):
public class DbDrivenPayloadHandlerBean {
int APPTS_FULLNAME_POS = -1;
int APPTS_DATETIME_POS = -1;
public DbDrivenPayloadHandlerBean() {
super();
}
public int getAPPTS_FULLNAME_POS() {
return APPTS_FULLNAME_POS;
}
public void setAPPTS_FULLNAME_POS(String APPTS_FULLNAME_POS) {
this.APPTS_FULLNAME_POS = Integer.parseInt(APPTS_FULLNAME_POS);
}
public int getAPPTS_DATETIME_POS() {
return APPTS_DATETIME_POS;
}
public void setAPPTS_DATETIME_POS(String APPTS_DATETIME_POS) {
this.APPTS_DATETIME_POS = Integer.parseInt(APPTS_DATETIME_POS);
}
Sorry guys, BeanUtils does the trick. I just don't want to be allowing setters that take Strings. I guess reflection does the casting for you. Apologies.
Solution as stated above: don't try to cast for BeanUtils.
public class DBDrivenPayloadHandler extends GDE{
DbDrivenPayloadHandlerBean bean;
#SuppressWarnings("rawtypes")
public void populateBean() throws Exception {
ITransaction trans = new MySQLTransaction();
IAdapterDataMapDAO adapterDataMap = new MySQLAdapterDataMapDAO();
adapterDataMap.setTransaction(trans);
HashMap<String, String> values = adapterDataMap.getHashMap(super.getCurrentAccountId());
this.bean = new DbDrivenPayloadHandlerBean();
Iterator it = values.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry)it.next();
try {
BeanUtils.setProperty(bean, (String) entry.getKey(), entry.getValue());
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void getInfo(String fileName) {
try {
populateBean();
} catch (Exception e) {
e.printStackTrace();
}
APPTS_FULLNAME_POS = bean.getAPPTS_FULLNAME_POS();
APPTS_DATETIME_POS = bean.getAPPTS_DATETIME_POS();
//Both still -1;
super.getInfo(filename);
}
Bean
public class DbDrivenPayloadHandlerBean {
int APPTS_FULLNAME_POS = -1;
int APPTS_DATETIME_POS = -1;
public DbDrivenPayloadHandlerBean() {
super();
}
public int getAPPTS_FULLNAME_POS() {
return APPTS_FULLNAME_POS;
}
public void setAPPTS_FULLNAME_POS(int APPTS_FULLNAME_POS) {
this.APPTS_FULLNAME_POS = APPTS_FULLNAME_POS;
}
public int getAPPTS_DATETIME_POS() {
return APPTS_DATETIME_POS;
}
public void setAPPTS_DATETIME_POS(String APPTS_DATETIME_POS) {
this.APPTS_DATETIME_POS = APPTS_DATETIME_POS;
}

Why object is becoming null when accessed out of thread

In the following program I'm inserting
files[i].lastModified() value in allFiles HashMap in RThread class
when I tried to retrive the value of lastModified from allFiles HashMap in the main class the value is coming as null. So instead of lastModified value I placed File object directly in HashMpa then it worked.
Anyone guide me the concept behind this.
import java.io.File;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
public class RCFLister {
ConcurrentHashMap allFiles = new ConcurrentHashMap();
String fileType = null;
/**
* #param args
*/
public static void main(String[] args) {
RCFLister rcFileLister = new RCFLister();
rcFileLister.recentFiles(args);
}
public void recentFiles(String[] args) {
int days = 1;
ThreadGroup rootthreadGr = new ThreadGroup("rootsThreadGroup");
// reading number of days
if (args.length > 0 && args[0] != null) {
days = Integer.valueOf(args[0]);
}
// reading file type
if (args.length > 0 && args[0] != null) {
fileType = args[1];
}
fileType = "png";
// fileextFilter = new FileExtensionFilter(fileType);
File[] roots = File.listRoots();
List threads = new ArrayList();
for (int i = 0; i < roots.length; i++) {
// System.out.println(roots[i].getAbsolutePath());
// rfThread = null;
RThread rfThread = new RThread(roots[i]);
Thread t = new Thread(rfThread);
t.start();
threads.add(t);
}
for (int i = 0; i < threads.size(); i++) {
try {
((Thread) threads.get(i)).join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
ValueComparator vc = new ValueComparator(allFiles);
TreeMap sortedMap = new TreeMap(vc);
sortedMap.putAll(allFiles);
System.out.println(sortedMap.size());
Iterator it = sortedMap.keySet().iterator();
while (it.hasNext()) {
Object key = it.next();
System.out.println(key + " " + sortedMap.get(key));
}
}
private class ValueComparator implements Comparator {
Map allFiles;
public ValueComparator(Map allFiles) {
this.allFiles = allFiles;
}
public int compare(Object o1, Object o2) {
if (((Long) allFiles.get(o1)) >= ((Long) allFiles.get(o2))) {
return -1;
} else {
return 1;
}
}
}
private class RThread implements Runnable {
File rootFolder;
RThread(File root) {
rootFolder = root;
}
public void run() {
getFiles(rootFolder);
}
public void getFiles(File folder) {
File[] files = folder.listFiles();
for (int i = 0; files != null && i < files.length; i++) {
// System.out.println(files[i].getAbsolutePath());
if (files[i].isDirectory()) {
getFiles(files[i]);
} else if (fileType == null
|| (fileType != null && files[i].getName().endsWith(
fileType))) {
String filename = null;
try {
filename = files[i].getCanonicalPath();
} catch (Exception e) {
e.printStackTrace();
}
if(files[i].lastModified()!=0)
allFiles.put(filename, files[i].lastModified());
}
}
}
}
}
compare() method of ValueComparator never returns 0. Return 0 means equality which is missing so even if key is present it is not found.
Also the key is String(filename) and you are comparing by value (long). Need to rethink how you want to store data.
Just to make sure it is only problem, print CocurrentHashMap.
Do use Generic, it looks tedious at beginning but is really not that bad. It will help to compiler code without warning and achieve type safety.

Java HashMap Create, edit and delete

I am trying to update a HashMap use it directly in the next method, but it isn't working. From what I read I couldn't find a solution. Some say'd it is impossible and some say use an iterator, but even with the iterator it's not working. the error is the printing method it is not printing or even getting inside the while loop because it is empty but i cant find why
This is the two methods I'm trying to update and print some information.
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class OrderList {
// Storage for an arbitrary number of details.
private HashMap<String, Order> orderList = new HashMap<String, Order>();
/**
* Perform any initialization .
*/
public OrderList() {
orderList = new HashMap<String, Order>();
}
public HashMap<String, Order> getOrders() {
return orderList;
}
public void readOrderFile(String OrderListPath) {
try {
File file = new File(OrderListPath);
Scanner scan = new Scanner(file);
while (scan.hasNextLine()) {
String readLine = scan.nextLine();
if (readLine != null) {
getSplitLinesOrders(readLine);
}
}
} catch (Exception e) {
}
}
public void getSplitLinesOrders(String readLine) {
String id = "";
String customerId = "";
String itemId = "";
int quantity = 0;
try {
String[] splitedLine = readLine.split(",");
if (splitedLine.length == 4) {
id = splitedLine[0];
customerId = splitedLine[1];
itemId = splitedLine[2];
quantity = Integer.parseInt(splitedLine[3]);
Order newOrder = new Order(id, customerId, itemId, quantity);
orderList.put(id, newOrder);
}
} catch (Exception e) {
}
}
/**
* Add a new set of details to the list
* #param details The details of the staff
*/
// public void addDetails(Order details) {
// orderList.add(details);
// }
public boolean hasOrder() {
return orderList.size() != 0;
}
public Order getNextOrder() {
Order order = orderList.remove(0);
return order;
}
/**
* #return All the details
*/
public String listDetails() {
StringBuffer allEntries = new StringBuffer();
for (Map.Entry<String, Order> details : orderList.entrySet()) {
String Key = details.getKey();
Object value = details.getValue();
allEntries.append(Key + " " + value);
}
return allEntries.toString();
}
public void PrintListOfOrders() {
Iterator it = getOrders().entrySet().iterator();
try {
while (it.hasNext()) {
Order value = (Order) it.next();
System.out.println(value.getOrderId() + " " + value.getCustomerId() + " " + value.getItemId() + " " + value.getQuantity());
}
} catch (Exception e) {
System.out.println(e);
}
}
}
You're probably getting a NullPointerException? Next time tell us what is going wrong and provide stacktraces if applicable.
The code you posted doesn't create an instance of orderList, so if it's not done elsewhere that code will throw a NullPointerException
Try adding:
private HashMap<String, Order> orderList = new HashMap<String, Order>;
Swallowing an Exception like this:
} catch (Exception e) {
}
is not a good practice since it will hide all information about what's going wrong, at least do:
catch (Exception e) {
e.printStacktrace();
}
You could do something like this:
Set<String> s = List.keySet();
Iterator<String> i = s.iterator();
Which is the initialization of the iterator, and then you could iterate through the keys using i.next(), getting a String each time and asking orderList.get(thatString) to get the value.

collections for sorting employee details by id & firstname

I have written a code to sort name by id and firstname.
import java.io.*;
import java.util.*;
public class TestEmployeeSort {
/**
* #param args
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
String option=null;
System.out.println("Enter on which order sorting should be done \n1.Id \n2.FirstName \n3.LastName");
List<Employee> coll = Name_Insert.getEmployees();
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
option=br.readLine();
int a=Integer.parseInt(option);
switch(a)
{
case 1:
Collections.sort(coll);
printList(coll);
break;
case 2:
Collections.sort(coll,new EmpSortByFirstName());// sort method
printList(coll);
break;
case 3:
Collections.sort(coll,new SortByLastName());// sort method
printList(coll);
}
}
private static void printList(List<Employee> list) {
System.out.println("EmpId\tFirstName\tLastName\tDate Of Joining\tDate of Birth");
for (int i=0;i<list.size();i++) {
Employee e=list.get(i);
System.out.println(e.getEmpId() + "\t" + e.getFirstName() + "\t" + e.getLastname() +"\t" + e.getDate_Of_Joining()+"\t"+e.getDate_Of_Birth());
}
}
}
for sorting by id and first name i have this code in the Sort_this class
public class EmpSortByFirstName implements Comparator<Employee>{
public int compare(Employee o1, Employee o2) {
return o1.getFirstName().compareTo(o2.getFirstName()); }}
similarly for id.
Now i want to change my program like i have to get input from uset on which basis you want to sort. If the user gives id, I have to sort by id. If the user gives firstname then sort by first name. I want to use if statement. If user enters 1 it has to sort by id 2 it has to sort by first name
Create a map of user input tokens (string, integer, etc.) to Comparator<Employee>, and just use the appropriate one.
Did you mean you want to get rid of using switch? If so, you can try having a map of registered soter:
import java.io.*;
import java.util.*;
public class TestEmployeeSort {
private static class EmployeeSortingManager {
private final List list;
private final Map<Integer, Comparator> registeredSorter = new HashMap<Integer, Comparator>();
public EmployeeSortingManager(List list) {
this.list = list;
registerAvailableSorters();
}
private void registerAvailableSorters() {
registeredSorter.put(1, null);
registeredSorter.put(2, new EmpSortByFirstName());
registeredSorter.put(3, new SortByLastName());
}
public void sortBy(int i) {
Comparator comparator = registeredSorter.get(i);
if (registeredSorter.get(i) != null) {
Collections.sort(list, comparator);
} else {
Collections.sort(list);
}
}
}
/**
* #param args
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
String option = null;
System.out.println("Enter on which order sorting should be done \n1.Id \n2.FirstName \n3.LastName");
List<Employee> coll = Name_Insert.getEmployees();
EmployeeSortingManager employeeSortingManager = new EmployeeSortingManager(coll);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
option = br.readLine();
int a = Integer.parseInt(option);
employeeSortingManager.sortBy(a);
printList(coll);
}
private static void printList(List<Employee> list) {
System.out.println("EmpId\tFirstName\tLastName\tDate Of Joining\tDate of Birth");
for (int i = 0; i < list.size(); i++) {
Employee e = list.get(i);
System.out.println(e.getEmpId() + "\t" + e.getFirstName() + "\t" + e.getLastname() + "\t" + e.getDate_Of_Joining() + "\t" + e.getDate_Of_Birth());
}
}
}
Another attemp to remove implementation of Every single comparator through the use of reflection. This is mmore complicated and may introduced more error if you are working with values which are not Comparable, e.g. String, Integer, Double. You will have to be careful.
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
public class TestEmployeeSort {
private static class EmployeeSortingManager {
private final List list;
private final Map<Integer, Method> registeredSorter = new HashMap();
private BasicComparator comparator = new BasicComparator();
public EmployeeSortingManager(List list) {
this.list = list;
registerAvailableSorters();
}
private void registerAvailableSorters() {
registeredSorter.put(1, null);
registeredSorter.put(2, getEmployeeGetMethod("firstName"));
registeredSorter.put(3, getEmployeeGetMethod("lastName"));
}
private Method getEmployeeGetMethod(String fieldName) {
Method method = null;
try {
// create java style get method name from field name, e.g. getFieldName from fieldName
String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
method = Employee.class.getMethod(getMethodName);
} catch (NoSuchMethodException ex) {
} catch (SecurityException ex) {
}
// null is return if you give invalid field name
return method;
}
public void sortBy(int i) {
Method get = registeredSorter.get(i);
if (get != null) {
comparator.setGetMethod(get);
Collections.sort(list, comparator);
} else {
Collections.sort(list);
}
}
}
private static class BasicComparator implements Comparator<Employee> {
private Method aGetMethod = null;
public void setGetMethod(Method aGetMethod) {
this.aGetMethod = aGetMethod;
}
#Override
public int compare(Employee o1, Employee o2) {
try {
Object value1 = aGetMethod.invoke(o1);
Object value2 = aGetMethod.invoke(o2);
if (value1 instanceof Comparable && value2 instanceof Comparable) {
// this should work with String, Integer, Double, etc. They all implement Comparable interface.
return ((Comparable) value1).compareTo((Comparable) value2);
} else {
// you will need to add your own comparision for other type of variable;
// obviously it is not possible to have a single comparison
// if your get method return something else.
}
} catch (IllegalAccessException ex) {
} catch (IllegalArgumentException ex) {
} catch (InvocationTargetException ex) {
}
// if cannot compare then they are equal.
return 0;
}
}
/**
* #param args
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
String option = null;
System.out.println("Enter on which order sorting should be done \n1.Id \n2.FirstName \n3.LastName");
List<Employee> coll = Name_Insert.getEmployees();
EmployeeSortingManager employeeSortingManager = new EmployeeSortingManager(coll);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
option = br.readLine();
int a = Integer.parseInt(option);
employeeSortingManager.sortBy(a);
printList(coll);
}
private static void printList(List<Employee> list) {
System.out.println("EmpId\tFirstName\tLastName\tDate Of Joining\tDate of Birth");
for (int i = 0; i < list.size(); i++) {
Employee e = list.get(i);
System.out.println(e.getEmpId() + "\t" + e.getFirstName() + "\t" + e.getLastname() + "\t" + e.getDate_Of_Joining() + "\t" + e.getDate_Of_Birth());
}
}
}

Categories