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.
Related
I am learning how to use sprint and to be honest I think it's useful when you know what to inject. I am having a dilemma on the following class:
package Edamam;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Properties;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.stereotype.Component;
#Component
public class EdamamApi {
private String ApplicationIDRecipes;
private String ApplicationKeyRecipes;
private String ApplicationIDIngredients;
private String ApplicationKeyIngredients;
public EdamamApi(){
Properties prop = new Properties();
InputStream input = null;
try{
input = new FileInputStream("src/main/java/Edamam/Edamam.properties");
prop.load(input);
this.ApplicationIDRecipes = prop.getProperty("Application_ID_Recipes");
this.ApplicationKeyRecipes = prop.getProperty("Application_Keys_Recipes");
this.ApplicationIDIngredients = prop.getProperty("Application_ID_Ingredients");
this.ApplicationKeyIngredients = prop.getProperty("Application_Keys_Ingredients");
}
catch(IOException ex){
ex.printStackTrace();
}finally{
if(input != null){
try{
input.close();
}
catch(IOException e){
e.printStackTrace();
}
}
}
}
private String makeUrlForRecipes(ArrayList<String> ingredients){
boolean isFirst = true;
String url = "https://api.edamam.com/search?q=";
for(String ingredient : ingredients){
if(!isFirst)
url = url + "%20";
isFirst = false;
url = url + ingredient;
}
url = url + "&app_id=" + this.ApplicationIDRecipes + "&app_key=" + this.ApplicationKeyRecipes;
return url;
}
private String makeUrlForIngredients(String ingredient){
String url = "https://api.edamam.com/api/nutrition-data?app_id="+this.ApplicationIDIngredients+
"&app_key="+this.ApplicationKeyIngredients+"&ingr=1%20large%20"+ingredient;
return url;
}
private ArrayList<String> toArrayList(JSONArray arr){
ArrayList<String> StringList = new ArrayList<String>();
for(int i = 0; i < arr.length(); i++)
StringList.add(arr.getString(i));
return StringList;
}
public ArrayList<RecipePojo> getRecipes(ArrayList<String> ingredients){
String url = makeUrlForRecipes(ingredients);
ArrayList<RecipePojo> recipes = new ArrayList<RecipePojo>();
try {
JSONObject response = JsonReader.readJsonFromUrl(url);
JSONArray jsonArray = response.getJSONArray("hits");
int NumberOfRecipes = 20;
int jsonIndex = 0;
while(jsonIndex < jsonArray.length() && NumberOfRecipes > 0){
JSONObject objectInArray = jsonArray.getJSONObject(jsonIndex);
String recipe = objectInArray.getJSONObject("recipe").getString("label");
String ImgURL = objectInArray.getJSONObject("recipe").getString("image");
ArrayList<String> IngredientLines = toArrayList(objectInArray.getJSONObject("recipe").
getJSONArray("ingredientLines"));
RecipePojo newRecipe = new RecipePojo(recipe, ImgURL, IngredientLines);
recipes.add(newRecipe);
jsonIndex++;
NumberOfRecipes--;
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return recipes;
}
public NutritionFactsIngredient getNutritionFacts(String ingredient){
String url = makeUrlForIngredients(ingredient);
System.out.println("the url is: " + url);
NutritionFactsIngredient facts = null;
try{
JSONObject response = JsonReader.readJsonFromUrl(url);
int Calories = response.getInt("calories");
int TotalWeight = response.getInt("totalWeight");
JSONArray DietLabelsJson = response.getJSONArray("dietLabels");
JSONArray HealthLabelsJson = response.getJSONArray("healthLabels");
JSONArray CautionsJson = response.getJSONArray("cautions");
ArrayList<String> DietLabels = this.toArrayList(DietLabelsJson);
ArrayList<String> HealthLabels = this.toArrayList(HealthLabelsJson);
ArrayList<String> Cautions = this.toArrayList(CautionsJson);
facts = new NutritionFactsIngredient(Calories,TotalWeight,
DietLabels,HealthLabels,Cautions, ingredient);
}catch (JSONException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
return facts;
}
}
I don't know if we should let spring handle the life-cycle of every object in our application. I just added the #component annotation on my class to get a taste of Spring, but I think that it's not enough. I am still instantiating objects with the new keyword inside of my methods. Should I make the classes RecipePojo and NutritionFactsIngredients components?. This is so confusing because the instances of these classes are not unique. They depend on user input. How can I use Spring on this class?
Edit: So people are telling me that instead of doing this:
#Component
public class EdamamApi{
public EdmamApi(){}
public Recipe getRecipe(String recipe ){
Recipe rep = Recipe(recipe);
return rep;
}
}
I should do this
#Component
public class EdamamApi{
public EdmamApi(){}
public void makeRecipe(String recipe, Recipe rep){
rep.setRecipeName(recipe);
}
}
In that way, the class is not tied down to Recipe and I can just use a bean Recipe.
--->THIS IS NOT RIGHT BUT IT'S WHAT I AM TRYING TO ACCOMPLISH <------
#Component
public class EdamamApi{
public EdmamApi(){}
public Recipe getRecipe(String name){
#Autowired
Recipe rep;
rep.setName(name);
return rep;
}
}
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
}
}
});
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();
}
}
}
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.
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());
}
}
}