Get value from hashmap/keyset in java? - java
I have code where I am placing two values into a Hashmap, and then accessing them from within another method. I am iterating through one value "dog", but at the end of the method, I need to print out the "race" relating to that "dog" value...
Here's what I have so far:
DecimalFormat df = new DecimalFormat("#.##");
for (String dog: data.keySet()) { // use the dog
String dogPage = "http://www.gbgb.org.uk/raceCard.aspx?dogName=" + dog;
Document doc1 = Jsoup.connect(dogPage).get();
// System.out.println("Dog name: " + dog);
Element tblHeader = doc1.select("tbody").first();
for (Element element1 : tblHeader.children()){
String position = element1.select("td:eq(4)").text();
int starts = (position.length() + 1) / 4;
int starts1 = starts;
// System.out.println("Starts: " + starts);
Pattern p = Pattern.compile("1st");
Matcher m = p.matcher(position);
int count = 0;
while (m.find()){
count +=1;
}
double firsts = count / (double)starts1 * 100;
String firstsStr = (df.format(firsts));
// System.out.println("Firsts: " + firstsStr + "%");
Pattern p2 = Pattern.compile("2nd");
Matcher m2 = p2.matcher(position);
int count2 = 0;
while (m2.find()){
count2 +=1;
}
double seconds = count2 / (double)starts1 * 100;
String secondsStr = (df.format(seconds));
// System.out.println("Seconds: " + secondsStr + "%");
Pattern p3 = Pattern.compile("3rd");
Matcher m3 = p3.matcher(position);
int count3 = 0;
while (m3.find()){
count3 +=1;
}
double thirds = count3 / (double)starts1 * 100;
String thirdsStr = (df.format(thirds));
// System.out.println("Thirds: " + thirdsStr + "%");
if (starts1 > 20 && firsts < 20 && seconds > 30 && thirds > 20){
System.out.println("Dog name: " + dog);
// System.out.println("Race: " + race);
System.out.println("Firsts: " + firstsStr + "%");
System.out.println("Seconds: " + secondsStr + "%");
System.out.println("Thirds: " + thirdsStr + "%");
System.out.println("");
}
}
Am I able to use something similar to "String dog: data.keySet())" to get the value of "Race"? for example: String race: data.keySet())?
Previous method:
Document doc = Jsoup.connect(
"http://www.sportinglife.com/greyhounds/abc-guide").get();
Element tableHeader = doc.select("tbody").first();
Map<String, String> data = new HashMap<>();
for (Element element : tableHeader.children()) {
// Here you can do something with each element
if (element.text().indexOf("Pelaw Grange") > 0
|| element.text().indexOf("Shawfield") > 0
|| element.text().indexOf("Shelbourne Park") > 0
|| element.text().indexOf("Harolds Cross") > 0) {
// do nothing
} else {
String dog = element.select("td:eq(0)").text();
String race = element.select("td:eq(1)").text();
data.put(dog, race);
}
Any help is much appreciated, thanks!
Rob
I am assuming that the value part of the HashMap is Race.
If yes, then you can do the following:
String race = data.get(dog);
in your current code, you are doing the following:
for (String dog: data.keySet()) { // use the dog
String race = data.get(dog); // this will give the value of race for the key dog
// using dog to do fetch details from site...
}
You could also do the following:
for (Entry<String, String> entry: data.entrySet()) {
String dog = entry.getKey();
String race = entry.getValue();
// using dog to do fetch details from site...
}
Related
How can I generated a list of data then query into the list?
I am new to Java and I am trying to build a Java command-line program, which generates random dataset (as in getData()) and query into the generated dataset. But I don't know how to pass the generated data from getData() function to the main function so that I can find the oldest person in my generated data. public class Data { public String first; public String last; public int age; public int id; public String country; public Data(String first, String last, int age, int id, String country) { this.first = first; this.last = last; this.age = age; this.id = id; this.country = country; } public String toString() { return "{" + " 'firstName': " + first + "," + " 'lastName': " + last + "," + " 'age': " + age + "," + " 'id': " + id + "," + " 'country': " + country + " }"; } public static ArrayList<Data> getData(int numRows) { ArrayList<Data> generator = new ArrayList<>(); String[] names = {"James", "Matt", "Olivia", "Liam", "Charlotte", "Amelia", "Evelyn", "Taeyeon", "Sooyoung", "Tiffany", "Yoona", "Hayley"}; String[] lastName = {"Novak", "Forbis", "Corner", "Broadbet", "Kim", "Young", "Hwang", "Choi", "McDonalds", "Kentucky", "Holmes", "Shinichi"}; String[] country = {"New Zealand", "Vietnam", "Korea", "French", "Japan", "Switzerland", "Italy", "Spain", "Thailand", "Singapore", "Malaysia", "USA"}; String data = ""; Random ran = new Random(); int namesLength = numRows; // passing length to names_len int lastNameLength = lastName.length; // passing length to lastname_len int countryLength = country.length; // passing length to lastname_len for (int i = 0; i < numRows; i++) { // for loop to iterate upto names.length int x = ran.nextInt(namesLength); // generating random integer int y = ran.nextInt(lastNameLength); // generating random integer int z = ran.nextInt(countryLength); int a = ran.nextInt(40); int exampleId = ran.nextInt(1000); // below for loop is to remove that element form names array for (int j = x; j < (namesLength - 1); j++) { names[j] = names[j + 1]; // this moves elements to one step back } // below for loop is to remove that element form Lastnames array for (int j = y; j < (lastNameLength - 1); j++) { lastName[j] = lastName[j + 1]; // this moves elements to one step back } for (int j = z; j < (countryLength - 1); j++) { country[j] = country[j + 1]; // this moves elements to one step back } namesLength = namesLength - 1; // reducing len of names_len by 1 lastNameLength = lastNameLength - 1; // reducing len of lastname_len by 1 countryLength = countryLength - 1; // reducing len of lastname_len by 1 // Output data in NDJSON format data = "{" + " 'firstName': " + names[x] + "," + " 'lastName': " + lastName[y] + "," + " 'age': " + a + "," + " 'id': " + exampleId + "," + " 'country': " + country[z] + " }"; System.out.println(data); // How can I add data to the generator list, the generator.add(data) does not work } // return a list of data return generator; } public static void main(String[] args) { // Generate random data int rows = 0; Scanner sc = new Scanner(System.in); System.out.print("Enter number of rows (maximum 12) you want to generate: "); rows = sc.nextInt(); while (rows >= 13 || rows <= 0) { System.out.println("Rows must be in range of 1 and 12"); System.out.print("Please reenter the number of rows: "); rows = sc.nextInt(); } System.out.println("Data is now generated"); ArrayList<Data> generatedData = getData(rows); String[] base_options = { "1 - Find the oldest person", "2 - Group by country and return count", "3 - Choose a country and group by age range", "4 - Find the youngest person", }; System.out.println(base_options); // Task 2 // TODO: PASTE GENERATED DATA INTO THIS // Find oldest Data oldest = generatedData.stream().max((a,b) -> a.age - b.age).get(); System.out.println(String.format("The oldest person is %s %s", oldest.first, oldest.last));
generator.add(new Data(names[x], lastName[y], a, exampleId, country[z])); works for me just fine
You can parse your generated data in string to Data and get the max valud like this: public static void main(String[] args) { // Generate random data int rows = 0; Scanner sc = new Scanner(System.in); System.out.print("Enter number of rows (maximum 12) you want to generate: "); rows = sc.nextInt(); while (rows >= 13 || rows <= 0) { System.out.println("Rows must be in range of 1 and 12"); System.out.print("Please reenter the number of rows: "); rows = sc.nextInt(); } System.out.println("Data is now generated"); ArrayList<String> generatedData = getData(rows); // Find oldest Data oldest = generatedData .stream() .map(it -> extractData(it)) .max(Comparator.comparingInt(a -> a.age)) .get(); System.out.println(String.format("The oldest person is %s %s", oldest.first, oldest.last)); } private static Data extractData(String str) { return new Data( extractProperty(str, "firstName"), extractProperty(str, "lastName"), Integer.parseInt(extractProperty(str, "age")), Integer.parseInt(extractProperty(str, "id")), extractProperty(str, "country") ); } private static String extractProperty(String str, String keyName) { String key = "'" + keyName + "': "; int startIndex = str.indexOf(key) + key.length(); if (startIndex < 0) { return ""; } StringBuilder value = new StringBuilder(); for (int i = startIndex ; i < str.length() ; ++i) { char ch = str.charAt(i); if (ch == ',') { break; } value.append(ch); } return value.toString(); }
Map some names and values using java
I have a set of values as a repsonse like this. from this 4,0,1581664239228,6,799,0,845,253,0,0,0,0,0,0,0,0,0,0,1448,594,0,1276257,0,0,0,0,1100,0,0,0,0,0,0,0,2047,2158,0,13,1 I have to map these values to below one..The order should be same like version: 4 , build: 0, tuneStartBaseUTCMS: 1581664239228 etc etc version,build,tuneStartBaseUTCMS,ManifestDLStartTime,ManifestDLTotalTime,ManifestDLFailCount,VideoPlaylistDLStartTime,VideoPlaylistDLTotalTime,VideoPlaylistDLFailCount,AudioPlaylistDLStartTime,AudioPlaylistDLTotalTime,AudioPlaylistDLFailCount,VideoInitDLStartTime,VideoInitDLTotalTime,VideoInitDLFailCount,AudioInitDLStartTime,AudioInitDLTotalTime,AudioInitDLFailCount,VideoFragmentDLStartTime,VideoFragmentDLTotalTime,VideoFragmentDLFailCount,VideoBitRate,AudioFragmentDLStartTime,AudioFragmentDLTotalTime,AudioFragmentDLFailCount,AudioBitRate,drmLicenseAcqStartTime,drmLicenseAcqTotalTime,drmFailErrorCode,LicenseAcqPreProcessingDuration,LicenseAcqNetworkDuration,LicenseAcqPostProcDuration,VideoFragmentDecryptDuration,AudioFragmentDecryptDuration,gstPlayStartTime,gstFirstFrameTime,contentType,streamType,firstTune I have written as follows...but it is not working as ex String abcd = "4,0,1581664239228,6,799,0,845,253,0,0,0,0,0,0,0,0,0,0,1448,594,0,1276257,0,0,0,0,1100,0,0,0,0,0,0,0,2047,2158,0,13,1"; String valueName = "version,build,tuneStartBaseUTCMS,ManifestDLStartTime,ManifestDLTotalTime,ManifestDLFailCount,VideoPlaylistDLStartTime,VideoPlaylistDLTotalTime,VideoPlaylistDLFailCount,AudioPlaylistDLStartTime,AudioPlaylistDLTotalTime,AudioPlaylistDLFailCount,VideoInitDLStartTime,VideoInitDLTotalTime,VideoInitDLFailCount,AudioInitDLStartTime,AudioInitDLTotalTime,AudioInitDLFailCount,VideoFragmentDLStartTime,VideoFragmentDLTotalTime,VideoFragmentDLFailCount,VideoBitRate,AudioFragmentDLStartTime,AudioFragmentDLTotalTime,AudioFragmentDLFailCount,AudioBitRate,drmLicenseAcqStartTime,drmLicenseAcqTotalTime,drmFailErrorCode,LicenseAcqPreProcessingDuration,LicenseAcqNetworkDuration,LicenseAcqPostProcDuration,VideoFragmentDecryptDuration,AudioFragmentDecryptDuration,gstPlayStartTime,gstFirstFrameTime,contentType,streamType,firstTune"; String[] valueArr = abcd.split(","); String[] valueNameArr = valueName.split(","); List<String> valueList = Arrays.asList(valueArr); List<String> valueNameList = Arrays.asList(valueNameArr); System.out.println(valueList.size() + "jjj: " + "valueNameList::: " + valueNameList.size()); LinkedHashMap<String, String> result = new LinkedHashMap<String, String>(); for (String name : valueNameList) { System.out.println("name: " + name); for (String value : valueList) { System.out.println("value: " + value); result.put(name, value); } } System.out.println("RESULT::::::::::::::::::::::::::::" + result); Result prints: {version=1, build=1, tuneStartBaseUTCMS=1, ManifestDLStartTime=1, ManifestDLTotalTime=1, ManifestDLFailCount=1, VideoPlaylistDLStartTime=1, VideoPlaylistDLTotalTime=1, VideoPlaylistDLFailCount=1, AudioPlaylistDLStartTime=1, AudioPlaylistDLTotalTime=1, AudioPlaylistDLFailCount=1, VideoInitDLStartTime=1, VideoInitDLTotalTime=1, VideoInitDLFailCount=1, AudioInitDLStartTime=1, AudioInitDLTotalTime=1, AudioInitDLFailCount=1, VideoFragmentDLStartTime=1, VideoFragmentDLTotalTime=1, VideoFragmentDLFailCount=1, VideoBitRate=1, AudioFragmentDLStartTime=1, AudioFragmentDLTotalTime=1, AudioFragmentDLFailCount=1, AudioBitRate=1, drmLicenseAcqStartTime=1, drmLicenseAcqTotalTime=1, drmFailErrorCode=1, LicenseAcqPreProcessingDuration=1, LicenseAcqNetworkDuration=1, LicenseAcqPostProcDuration=1, VideoFragmentDecryptDuration=1, AudioFragmentDecryptDuration=1, gstPlayStartTime=1, gstFirstFrameTime=1, contentType=1, streamType=1, firstTune=1}
Your loop is wrong Try this for(int i = 0; i < valueList.size(); i++){ result.put(valueNameList(i), valueList(i)); }
Is there not supposed to be a one-to-one relationship between abcd values and valueName ? If there is one-to-one, then an inner loop is wrong isn't it. String abcd = "4,0,1581664239228,6,799,0,845,253,0,0,0,0,0,0,0,0,0,0,1448,594,0,1276257,0,0,0,0,1100,0,0,0,0,0,0,0,2047,2158,0,13,1"; String valueName = "version,build,tuneStartBaseUTCMS,ManifestDLStartTime,ManifestDLTotalTime,ManifestDLFailCount,VideoPlaylistDLStartTime,VideoPlaylistDLTotalTime,VideoPlaylistDLFailCount,AudioPlaylistDLStartTime,AudioPlaylistDLTotalTime,AudioPlaylistDLFailCount,VideoInitDLStartTime,VideoInitDLTotalTime,VideoInitDLFailCount,AudioInitDLStartTime,AudioInitDLTotalTime,AudioInitDLFailCount,VideoFragmentDLStartTime,VideoFragmentDLTotalTime,VideoFragmentDLFailCount,VideoBitRate,AudioFragmentDLStartTime,AudioFragmentDLTotalTime,AudioFragmentDLFailCount,AudioBitRate,drmLicenseAcqStartTime,drmLicenseAcqTotalTime,drmFailErrorCode,LicenseAcqPreProcessingDuration,LicenseAcqNetworkDuration,LicenseAcqPostProcDuration,VideoFragmentDecryptDuration,AudioFragmentDecryptDuration,gstPlayStartTime,gstFirstFrameTime,contentType,streamType,firstTune"; String[] list1 = abcd.split(","); String[] list2 = valueName.split(","); if (list1.length == list2.length) { for (int x = 0; x < list1.length; x++) { System.out.println(list2[x] + ":" + list1[x]); } } Simply split and iterate result version:4 build:0 tuneStartBaseUTCMS:1581664239228 ManifestDLStartTime:6 ManifestDLTotalTime:799 ManifestDLFailCount:0 VideoPlaylistDLStartTime:845 VideoPlaylistDLTotalTime:253 VideoPlaylistDLFailCount:0 AudioPlaylistDLStartTime:0 AudioPlaylistDLTotalTime:0 AudioPlaylistDLFailCount:0 VideoInitDLStartTime:0 VideoInitDLTotalTime:0 VideoInitDLFailCount:0 AudioInitDLStartTime:0 AudioInitDLTotalTime:0 AudioInitDLFailCount:0 VideoFragmentDLStartTime:1448 VideoFragmentDLTotalTime:594 VideoFragmentDLFailCount:0 VideoBitRate:1276257 AudioFragmentDLStartTime:0 AudioFragmentDLTotalTime:0 AudioFragmentDLFailCount:0 AudioBitRate:0 drmLicenseAcqStartTime:1100 drmLicenseAcqTotalTime:0 drmFailErrorCode:0 LicenseAcqPreProcessingDuration:0 LicenseAcqNetworkDuration:0 LicenseAcqPostProcDuration:0 VideoFragmentDecryptDuration:0 AudioFragmentDecryptDuration:0 gstPlayStartTime:2047 gstFirstFrameTime:2158 contentType:0 streamType:13 firstTune:1
This method must return a result of type String, Java
I'm pretty new to Java. Eclipse is giving me the error This method must return a result of type I want to return the String str, if I put str after all the for-loops I would get local variable not initialized. How could I code it so that public String getQuadraticFactors() { String str; ArrayList<Integer> prFactors = new ArrayList<Integer>(); ArrayList<Integer> qsFactors = new ArrayList<Integer>(); ArrayList<Integer> p = getPRIntegerFactors(a), r = getPRIntegerFactors(a), q = getQSIntegerFactors(c), s = getQSIntegerFactors(c); System.out.println(p + "*********" + q); System.out.println(p.get(0)); // String str2 = "jjjhljl"; String str2 = "(" + p + "x + " + q + ")(" + r + "x +" + s + ")"; for (int k = 0; k < p.size(); k++) { // System.out.print(k); for (int l = 0; l < q.size(); l++) { // System.out.print(k); for (int m = 0; m < p.size(); m++) { for (int n = 0; n < q.size(); n++) { if (p.get(k) * r.get(m) == a && p.get(k) * s.get(n) + q.get(l) * r.get(m) == b && q.get(l) * s.get(n) == c) { System.out.println(a); System.out.println(p.get(k) * r.get(m)); return str = "(" + p.get(k) + "x + " + q.get(l) + ")(" + r.get(m) + "x + " + s.get(n) + ")"; } } } } } }
there is a slight possibility that you will never hit your return statement. To fix this, just add a return statement to the very bottom of your method that returns a empty string or whatever value you would like to send to say that if (p.get(k) * r.get(m) == a && p.get(k) * s.get(n) + q.get(l) * r.get(m) == b && q.get(l) * s.get(n) == c) this if statement is false for all cases. Sometimes you will never run into a situation where this if statement is false, but the JVM just needs reassurance that it has something to return if it is false.
Actually you need to have an alternative when some of your for-loops don't run. Just initialise your str with some value of better yet, check it at the bottom. If it is null throw an exception or initialize it (depending on your code style). When you check before returning it will always have a value (or you throw an exception).
java-how to return multiple values in an array in switch case
I want to return all the array elements which satisfies the if statement in the code above. Here the output is all the first element which satisfies the if condition. switch(ch) { case 1: { g = prob1 * totoutcome; flag = (int) g; for(int i=0; i<9; i++) { if(a1[0][0].equals(veh[i]) && flag > 0) { flag--; return(id[i] + " " + name[i] + " " + number[i] + " " + veh[i] + " " + color[i] + " " + type[i] + "\n"); } } break; }
return means go back to the function that called you (and not go back and come back to return another) carrying the variable returned. To achieve what you want.. you can create a list, add the elements to return to the list and return the list after ending your for loop.
ArrayList<String> aa = new ArrayList<String>(); ArrayList<String> ab = new ArrayList<String>(); ArrayList<String> ac = new ArrayList<String>(); ArrayList<String> ad = new ArrayList<String>(); ArrayList<String> ae = new ArrayList<String>(); for(.....) { if() { aa.add(name[i]); ab.add(number[i]); ac.add(veh[i]); ad.add(color[i]); ae.add(type[i]); } } return(aa+ab+ac+ad+ae);
Remove Data and Arraylist looping
I have a object with 3 variable (id(string), year(int), pay(double)) I have created an arraylist that contains object. So now I need to sum the the pay if they have the same id and year and store it in a new array! is that possible? ArrayList<Earning> temp = new ArrayList(); ArrayList<Earning> temp = new ArrayList(); double tempEarning = 0.0; int count = 0; for (int i = 0; i < weeklyEarnings.size(); i++) { Earning e = weeklyEarnings.get(i); String id = e.getId(); int year = e.getYear(); tempEarning = e.getEarning(); Earning e2 = weeklyEarnings.get(i + 1); if (id.equalsIgnoreCase(e2.getId()) && year == e2.getYear()) { tempEarning += e2.getEarning(); } else { Earning tempEarn = new Earning(); tempEarn.setEarning(tempEarning); tempEarn.setId(id); tempEarn.setYear(year); temp.add(tempEarn); count++; tempEarning = 0.0; } } weeklyEarnings.clear(); weeklyEarnings = temp; temp.clear(); Can someone Help me? Thanks a lot!
Try this: HashMap<String, Earning> totalEarnings = new HashMap<String, Earning>(); for (Earning earning : weeklyEarnings) { Earning tmpEarning = totalEarnings.get(earning.getId() + earning.getYear()); if (tmpEarning == null) { tmpEarning = new Earning(); tmpEarning.setId(earning.getId()); tmpEarning.setYear(earning.getYear()); totalEarnings.put(earning.getId() + earning.getYear(), tmpEarning); } tmpEarning.setEarning(tmpEarning.getEarning() + earning.getEarning()); } for (Earning earning : totalEarnings.values()) { System.out.println(earning.getId() + ' ' + earning.getyear() + ' ' + earning.getEarning()); }
You can do it like this. Iterate through the list. Match each item in the list with one id. If match found "Sum Pay". Continue for each item in the list.