Related
I am trying to read a text file and store with a hashmap. The file contains information like this:
1946-01-12;13:00:00;0.3;G
1946-01-12;18:00:00;-2.8;G
1946-01-13;07:00:00;-6.2;G
1946-01-13;13:00:00;-4.7;G
1946-01-13;18:00:00;-4.3;G
1946-01-14;07:00:00;-1.5;G
1946-01-14;13:00:00;-0.2;G
I want to store the dates as keys and then "13:00:00;0.3;G" as value, where 13:00 is time, 0.3 is temperature and G represent a quality code. I wonder if this is even possbile since many rows in the file has the same date? I already wrote a code for storing the data in a list, but now I want to store it in a map instead. My old code looks like this:
/**
* Provides methods to retrieve temperature data from a weather station file.
*/
public class WeatherDataHandler {
private List<Weather> weatherData = new ArrayList<>();
public void loadData(String filePath) throws IOException {
List<String> fileData = Files.readAllLines(Paths.get("filepath"));
for(String str : fileData) {
List<String> parsed = parseData(str);
LocalDate date = LocalDate.parse(parsed.get(0));
LocalTime time = LocalTime.parse(parsed.get(1));
double temperature = Double.parseDouble(parsed.get(2));
String quality = parsed.get(3);
//new Weather object
Weather weather = new Weather(date, time, temperature, quality);
weatherData.add(weather);
}
}
private List<String> parseData(String s) {
return Arrays.asList(s.split(";"));
}
I got stuck when implementing the hashmap. I started with some code below, but I do not know how to loop over a sequence of dates. What is the simplest way to store the data from the file in a map?
public class WeatherDataHandler {
public void loadData(String filePath) throws IOException {
Map<LocalDate, String> map =new HashMap<LocalDate, String>();
BufferedReader br = new BufferedReader(new FileReader("filepath"));
String line="";
int i=0;
while (line != null) {
line = br.readLine();
map.put(i,line);
i++;
}
String date="";
String time="";
String temperature="";
String quality="";
for(int j=0;j<map.size();j++){
if(!(map.get(j)== null)){
String[] getData=map.get(j).toString().split("\\,");
date = getData[0];
time = getData[1];
temperature = getData[2];
quality = getData[3];
}
}
}
Using the stream API you can create a map where the key is the date and the [map] value is a list.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class WeatherDataHandler {
public static void main(String[] args) {
Path path = Paths.get("filepath");
try {
Map<String, List<String>> map = Files.lines(path)
.collect(Collectors.groupingBy(line -> line.split(";", 2)[0]));
map.entrySet()
.stream()
.forEach(entry -> System.out.printf("%s = %s%n", entry.getKey(), entry.getValue()));
}
catch (IOException x) {
x.printStackTrace();
}
}
}
Method lines() in class java.nio.file.Files creates a stream where each stream element is a single line of the file being read.
Method split() splits the line into a two element array (because of the second argument which is the number 2).
The first array element, i.e. the date, becomes the [map] key and the rest of the line becomes the [map] value.
Whenever a duplicate key is encountered, the value is appended to the existing value creating a list. Hence the type parameters for the map are String for the [map] key and List<String> for the [map] value.
Running the above code on your sample data yields:
1946-01-14 = [1946-01-14;07:00:00;-1.5;G, 1946-01-14;13:00:00;-0.2;G]
1946-01-12 = [1946-01-12;13:00:00;0.3;G , 1946-01-12;18:00:00;-2.8;G]
1946-01-13 = [1946-01-13;07:00:00;-6.2;G , 1946-01-13;13:00:00;-4.7;G, 1946-01-13;18:00:00;-4.3;G ]
I have a CSV file and I need to sort the content by two columns. The first column is a date and the fourth is text. I need that file sorted by first and fourth column.
I'm trying like this:
//i read file and iterate in lines
PriorityQueue<String[]> linesOrdenered = new PriorityQueue<>(new LineComparator());
while ((line = br.readLine()) != null) {
String[] row = line.split(CVS_SPLIT_BY);
if ((!isHeader) && row[0].equals("Route Date")) {
header = line;
isHeader = true;
continue;
}
linesOrdenered.add(row);
}
public class LineComparator implements Comparator<String[]> {
//string[3] == key
#Override
public int compare(String[] strings, String[] t1) {
int keyComparator = 0;
try {
Date dataOne = format.parse(strings[0]);
Date dataTwo = format.parse(t1[0]);
keyComparator = dataOne.compareTo(dataTwo);
} catch (ParseException e) {
LOGGER.error("Error on parse Data [{}]", e.getMessage());
}
if (keyComparator == 0) {
keyComparator = strings[3].compareTo(t1[3]);
}
return keyComparator;
}
}
The result is a PriorityQueue with just date being ordered.
Example content of CSV file:
12/01/2018,6:30,C-993BNT,A1001
12/03/2018,6:30,C-993BNT,A1001
12/04/2018,6:30,C-993BNT,A1001
12/05/2018,6:30,C-993BNT,A1001
12/01/2018,6:30,C-555BQJ,A1003
12/03/2018,6:30,C-555BQJ,A1003
12/04/2018,6:30,C-555BQJ,A1003
12/05/2018,6:30,C-555BQJ,A1003
12/06/2018,6:30,C-555BQJ,A1003
12/07/2018,6:30,C-555BQJ,A1003
Your input file and "format" are not available for us but my educated guess is that all dates are different when parsed using the format (at least to the extent that comparing them does not return 0).
Carrying on with Roy Shahaf's idea, assuming :
private static DateFormat format = new SimpleDateFormat("MM/dd/yyyy");
I get:
12/01/2018,6:30,C-993BNT,A1001
12/01/2018,6:30,C-555BQJ,A1003
12/03/2018,6:30,C-993BNT,A1001
12/03/2018,6:30,C-555BQJ,A1003
12/04/2018,6:30,C-993BNT,A1001
12/04/2018,6:30,C-555BQJ,A1003
12/05/2018,6:30,C-993BNT,A1001
12/05/2018,6:30,C-555BQJ,A1003
12/06/2018,6:30,C-555BQJ,A1003
12/07/2018,6:30,C-555BQJ,A1003
which looks right to me. see https://jdoodle.com/a/QXP
I am pretty new into programming and I have an assignment to make, but I got stuck.
I have to implement a program which will read a CSV file (1 million+ lines) and count how many clients ordered "x" distinct products on a specific day.
The CSV looks like this:
Product Name | Product ID | Client ID | Date
Name 544 86 10/12/2017
Name 545 86 10/12/2017
Name 644 87 10/12/2017
Name 644 87 10/12/2017
Name 9857 801 10/12/2017
Name 3022 801 10/12/2017
Name 3021 801 10/12/2017
The result from my code is:
801: 2 - incorrect
86: 2 - correct
87: 2 - incorrect
Desired output is:
Client 1 (801): 3 distinct products
Client 2 (86): 2 distinct products
Client 3 (87): 1 distinct product
Additionally,
If I want to know how many clients ordered 2 distinct products I would like a result to look like this:
Total: 1 client ordered 2 distinct products
If I want to know the maximum number of distinct products ordered in a day, I would like the result to look like this:
The maximum number of distinct products ordered is: 3
I tried to use a Hash Map and Multimap by Google Guava (my best guess here), but I couldn't wrap my head around it.
My code looks like this:
package Test;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.HashMultimap;
public class Test {
public static void main(String[] args) {
//HashMultimap<String, String> myMultimap = HashMultimap.create();
Map<String, MutableInteger> map = new HashMap<String, MutableInteger>();
ArrayList<String> linesList = new ArrayList<>();
// Input of file which needs to be parsed
String csvFile = "file.csv";
BufferedReader csvReader;
// Data split by 'TAB' in CSV file
String csvSplitBy = "\t";
try {
// Read the CSV file into an ArrayList array for easy processing.
String line;
csvReader = new BufferedReader(new FileReader(csvFile));
while ((line = csvReader.readLine()) !=null) {
linesList.add(line);
}
csvReader.close();
} catch (IOException e) {
e.printStackTrace();
}
// Process each CSV file line which is now contained within
// the linesList list Array
for (int i = 0; i < linesList.size(); i++) {
String[] data = linesList.get(i).split(csvSplitBy);
String col2 = data[1];
String col3 = data[2];
String col4 = data[3];
// Determine if Column 4 has the desired date
// and count the values
if (col4.contains("10/12/2017")) {
String key = col3;
if (map.containsKey(key)) {
MutableInteger count = map.get(key);
count.set(count.get() + 1);
} else {
map.put(key, new MutableInteger(1));
}
}
}
for (final String k : map.keySet()) {
if (map.get(k).get() == 2) {
System.out.println(k + ": " + map.get(k).get());
}
}
}
}
Any advise or suggestion on how this can be implemented would be greatly appreciated.
Thank you in advance guys.
You could store a Setof productIds per clientId, and just take the size of that.
As a Set does not allow duplicate values, this will effectively give you the distinct number of productIds.
Also, I recommend that you give your variables meaningful name instead of col2, k, map... This will make your code more readable.
Map<String, Set<String>> distinctProductsPerClient = new HashMap<String, Set<String>>();
// Process each CSV file line which is now contained within
// the linesList list Array
// Start from 1 to skip the first line
for (int i = 1; i < linesList.size(); i++) {
String line = linesList.get(i);
String[] data = line.split(csvSplitBy);
String productId = data[1];
String clientId = data[2];
String date = data[3];
// Determine if Column 4 has the desired date
// and count the values
if (date.contains("10/12/2017")) {
if (!distinctProductsPerClient.containsKey(clientId)) {
distinctProductsPerClient.put(clientId, new HashSet<>());
}
distinctProductsPerClient.get(clientId).add(productId);
}
}
for (final String clientId : distinctProductsPerClient.keySet()) {
System.out.println(clientId + ": " + distinctProductsPerClient.get(clientId).size());
}
More advanced solution using Stream API (requires Java 9)
If you introduce the class OrderData(that represents a single line in the CSV) like this:
private static class OrderData {
private final String productName;
private final String productId;
private final String clientId;
private final String date;
public OrderData(String csvLine) {
String[] data = csvLine.split("\t");
this.productName = data[0];
this.productId = data[1];
this.clientId = data[2];
this.date = data[3];
}
public String getProductName() {
return productName;
}
public String getProductId() {
return productId;
}
public String getClientId() {
return clientId;
}
public String getDate() {
return date;
}
}
you can replace the for loop with this:
Map<String, Set<String>> distinctProductsPerClient2 = linesList.stream()
.skip(1)
.map(OrderData::new)
.collect(groupingBy(OrderData::getClientId, mapping(OrderData::getProductId, toSet())));
But I reckon this might be a little bit to complex if you're new into programming (although it might be a good exercise if you would try to understand what the above code does).
Hello I am trying to figure out the big 0 notation for my code but having trouble with it. I am new to algorithms and don't know what processes increase 0(n) to 0(n2) for example.
package gmit;
import java.util.*;
import java.io.*;
import java.nio.charset.Charset;
public class TestRunner {
// Creating Hashmap
private static HashMap<String, String> stringmap = new HashMap<String, String>();
// Creating String Array lists
private static ArrayList<ArrayList<String>> mylist = new ArrayList<ArrayList<String>>();
private static ArrayList<String> lol = new ArrayList<String>();
// Declaring int variables
private static int encryptioncounter=0,decryptioncounter=0,lastindexcounter=0,
mylistindexcounter=0,resortcounter=0;
// Declaring String variables
private static String password,value;
private static String result,text;
// ----------------------------------------------- Main start --------------------------------------------------------
public static void main(String[] args) throws IOException {
System.out.println("Pleaseinput your passphrase");
// Gets user Input
Scanner in = new Scanner(System.in);
password = in.nextLine();
System.out.println("Please input the file name you want to encrypt.(WarAndPeace-LeoTolstoy.txt)");
// Gets user Input
Scanner tin = new Scanner(System.in);
text = tin.nextLine();
//Starts Timer
long startTime = System.nanoTime();
// Method to populate HashMap
putstuffinstrinmap();
// Starts for loop
// Creates Array list in number of the amount of characters of the password
// Adds created arraylists to Arraylist<List> mylist.
for (int i = 0; i < password.length(); i++) {
List<String> firstCharandMore= new ArrayList<>();
char c = password.charAt(i);
firstCharandMore.add(String.valueOf(c));
String resortcountertostring= String.valueOf(resortcounter);
mylist.add((ArrayList<String>) firstCharandMore);
// Adds index for resort to arraylists
mylist.get(i).add(resortcountertostring);
//mylist.add((ArrayList<String>) resortcountertostring);
resortcounter++;
}
// Reads in File in UTF-8 format
// gets back a character
BufferedReader reader = new BufferedReader(
new InputStreamReader(
new FileInputStream(text),
Charset.forName("UTF-8")));
int c;
while((c = reader.read()) != -1) {
char string = (char) c;
// Converts Character to upper case String
// Passes the string into encryption method
encrypt(Character.toString(string).toUpperCase());
// Adds one to counter
decryptioncounter++;
}
//long endTime2 = System.nanoTime();
//long totalTime2 = endTime2 - startTime;
//double seconds2 = (double)totalTime2 / 1000000000.0;
//System.out.println(seconds2+" Encryption");
// Creates new Arraylist listToSort (Copy of mylist)
// Sorts Array lists in alphabetic order by first character from each list
sortarraylists();
writetofileencrypted();
// Resorts arraylists using the index
resortarraylist();
// Calls decryption method
decrypt();
// Calls write to file method
writetofilefin();
// Ends Timer
long endTime = System.nanoTime();
long totalTime = endTime - startTime;
// Prints Time
double seconds = (double)totalTime / 1000000000.0;
System.out.println(seconds+" Total time");
}
// ------------------------------------ End Main -----------------------------------------
// Writes encrypted message to file.
private static void writetofileencrypted() throws FileNotFoundException, UnsupportedEncodingException {
// TODO Auto-generated method stub
PrintWriter writer2 = new PrintWriter("encrypted.txt", "UTF-8");
StringBuilder builder2 = new StringBuilder();
for (ArrayList<String> value : mylist) {
builder2.append(value);
}
String s = builder2.toString();
//String s = lol.toString();
writer2.println(s);
writer2.close();
}
// -------------------------------------resorting-----------------------------------------
private static void resortarraylist() {
// Resorts lists using index 1 (The numbers assigned to that index))
mylist.sort((l1, l2) -> l1.get(1).compareTo(l2.get(1)));
}
// ------------------------------------End resorting --------------------------------------
// ------------------------------------ Sorting ------------------------------------------
private static void sortarraylists() {
// Sorting lists in alphabetical order by index 0
mylist.sort((l1, l2) -> l1.get(0).compareTo(l2.get(0)));
}
// ------------------------------------End sorting ---------------------------------------
// ------------------------------------write to file --------------------------------------
private static void writetofilefin() throws FileNotFoundException, UnsupportedEncodingException {
// Prints to array list lol to file
PrintWriter writer = new PrintWriter("finished.txt", "UTF-8");
StringBuilder builder = new StringBuilder();
for (String value : lol) {
builder.append(value);
}
String s = builder.toString();
//String s = lol.toString();
writer.println(s);
writer.close();
}
// -------------------------------- Encryption Start -------------------------------------
private static void encrypt(String string) {
// Gets coherent value from map
value= stringmap.get(string);
// adds value to mylist at index encryptioncounter
mylist.get(encryptioncounter).add(value);
// Adds one to counter
encryptioncounter++;
// Resets encryptioncounter
if(encryptioncounter>=password.length()){
encryptioncounter=0;
// Adds one to lastindexcounter
lastindexcounter++;
}
}
// --------------------------------- Encryption End ---------------------------------------
// --------------------------------- Decryption Start -------------------------------------
private static void decrypt() {
int thiscounter=0;
// runs until decryptioncounter is = to thiscounter or
// mylistindexcounter is = to lastindexcounter
while(decryptioncounter != thiscounter ){
for(int i=0;i <password.length() ;i++){
// gets value from Arraylist
String ba = mylist.get(i).get(mylistindexcounter);//0(1)
// gets coherent value from map
result= stringmap.get(ba);// 0(n)
// adds value to arraylist lol
lol.add(result);
thiscounter++;
if(mylistindexcounter >=lastindexcounter){
decryptioncounter =thiscounter;
}
}
mylistindexcounter++;
}
}
// ---------------------------------- Decryption End ---------------------------------------
// --------------------------------- Map population start ---------------------------------
// 0(1)
public static void putstuffinstrinmap(){
stringmap.put("AA", "P");//AA - P
stringmap.put("AD", "H");//AD - H
stringmap.put("AF", "0");//
stringmap.put("AG", "Q");//
stringmap.put("AV", "G");//
stringmap.put("AX", "6");//
stringmap.put("DA", "4");//
stringmap.put("DD", "M");//
stringmap.put("DF", "E");//
stringmap.put("DG", "A");//
stringmap.put("DV", "1");//
stringmap.put("DX", "Y");//
stringmap.put("FA", "L");//
stringmap.put("FD", "2");//
stringmap.put("FF", "N");//
stringmap.put("FG", "O");//
stringmap.put("FV", "F");//
stringmap.put("FX", "D");//
stringmap.put("GA", "X");//
stringmap.put("GD", "K");//
stringmap.put("GF", "R");//
stringmap.put("GG", "3");//
stringmap.put("GV", "C");//
stringmap.put("GX", "V");//
stringmap.put("VA", "S");//
stringmap.put("VD", "5");//
stringmap.put("VF", "Z");//
stringmap.put("VG", "W");//
stringmap.put("VV", "7");//
stringmap.put("VX", "B");//
stringmap.put("XA", "J");//
stringmap.put("XD", "9");//
stringmap.put("XF", "U");//
stringmap.put("XG", "T");//
stringmap.put("XV", "I");//
stringmap.put("XX", "8");//
stringmap.put("P", "AA");//
stringmap.put("H", "AD");//
stringmap.put("0", "AF");//
stringmap.put("Q", "AG");//
stringmap.put("G", "AV");//
stringmap.put("6", "AX");//
stringmap.put("4", "DA");//
stringmap.put("M", "DD");//
stringmap.put("E", "DF");//
stringmap.put("A", "DG");//
stringmap.put("1", "DV");//
stringmap.put("Y", "DX");//
stringmap.put("L", "FA");//
stringmap.put("2", "FD");//
stringmap.put("N", "FF");//
stringmap.put("O", "FG");//
stringmap.put("F", "FV");//
stringmap.put("D", "FX");//
stringmap.put("X", "GA");//
stringmap.put("K", "GD");//
stringmap.put("R", "GF");//
stringmap.put("3", "GG");//
stringmap.put("C", "GV");//
stringmap.put("V", "GX");//
stringmap.put("S", "VA");//
stringmap.put("5", "VD");//
stringmap.put("Z", "VF");//
stringmap.put("W", "VG");//
stringmap.put("7", "VV");//
stringmap.put("B", "VX");//
stringmap.put("J", "XA");//
stringmap.put("9", "XD");//
stringmap.put("U", "XF");//
stringmap.put("T", "XG");//
stringmap.put("I", "XV");//
stringmap.put("8", "XX");//
stringmap.put("AH", ".");//
stringmap.put("DH", "!");//
stringmap.put("FH", "?");//
stringmap.put("GH", " ");//
stringmap.put("VH", "'");//
stringmap.put("XH", ",");//
stringmap.put(".", "AH");//
stringmap.put("!", "DH");//
stringmap.put("?", "FH");//
stringmap.put(" ", "GH");//
stringmap.put("'", "VH");//
stringmap.put(",", "XH");//
stringmap.put("AP", "]");//
stringmap.put("DP", "[");//
stringmap.put("FP", "~");//
stringmap.put("GP", "&");//
stringmap.put("VP", ":");//
stringmap.put("XP", ";");//
stringmap.put("AP", "-");//"
stringmap.put("DP", "");//
stringmap.put("FP", "*");//
stringmap.put("GP", "^");//
stringmap.put("VP", "\"");//
stringmap.put(null, " ");//
}
// --------------------------------- Map population End -----------------------------------
}
Any help explaining it using my code or guiding me to some reading material would be greatly appreciated.
First of all, you don't need a Total time to find a Big O. Big O notation is use to find count of elementary operations in algorithm. Like write n elements of array is O(n) because you need write every element. For matrix of size n*n it's O(n^2). I think, so i your algorithm Big O is O(nm+k). Where n is count of steps while(decryption counter!= thecounter) loop, m is length of password and k is other operations, loops. Usually k don't add to Big O because is much smaller than nm, but in your case I'm not sure about it.
I am working on a project where I have been given a text file and I have to add up the points for each team and printout the top 5 teams.
The text file looks like this:
FRAMae Berenice MEITE 455.455<br>
CHNKexin ZHANG 454.584<br>
UKRNatalia POPOVA 453.443<br>
GERNathalie WEINZIERL 452.162<br>
RUSEvgeny PLYUSHCHENKO 191.399<br>
CANPatrick CHAN 189.718<br>
CHNHan YAN 185.527<br>
CHNCheng & Hao 271.018<br>
ITAStefania & Ondrej 270.317<br>
USAMarissa & Simon 264.256<br>
GERMaylin & Daniel 260.825<br>
FRAFlorent AMODIO 179.936<br>
GERPeter LIEBERS 179.615<br>
JPNYuzuru HANYU 197.9810<br>
USAJeremy ABBOTT 165.654<br>
UKRYakov GODOROZHA 160.513<br>
GBRMatthew PARR 157.402<br>
ITAPaul Bonifacio PARKINSON 153.941<br>
RUSTatiana & Maxim 283.7910<br>
CANMeagan & Eric 273.109<br>
FRAVanessa & Morgan 257.454<br>
JPNNarumi & Ryuichi 246.563<br>
JPNCathy & Chris 352.003<br>
UKRSiobhan & Dmitri 349.192<br>
CHNXintong &Xun 347.881<br>
RUSYulia LIPNITSKAYA 472.9010<br>
ITACarolina KOSTNER 470.849<br>
JPNMao ASADA 464.078<br>
UKRJulia & Yuri 246.342<br>
GBRStacey & David 244.701<br>
USAMeryl &Charlie 375.9810<br>
CANTessa & Scott 372.989<br>
RUSEkaterina & Dmitri 370.278<br>
FRANathalie & Fabian 369.157<br>
ITAAnna & Luca 364.926<br>
GERNelli & Alexander 358.045<br>
GBRPenny & Nicholas 352.934<br>
USAAshley WAGNER 463.107<br>
CANKaetlyn OSMOND 462.546<br>
GBRJenna MCCORKELL 450.091<br>
The first three letters represent the team.
the rest of the text is the the competitors name.
The last digit is the score the competitor recived.
Code so far:
import java.util.Arrays;
public class project2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] array = new String[41];
String[] info = new String[41];
String[] stats = new String[41];
String[] team = new String[41];
//.txt file location
FileInput fileIn = new FileInput();
fileIn.openFile("C:\\Users\\O\\Desktop\\turn in\\team.txt");
// txt file to array
int i = 0;
String line = fileIn.readLine();
array[i] = line;
i++;
while (line != null) {
line = fileIn.readLine();
array[i] = line;
i++;
}
//Splitting up Info/team/score into seprate arrays
for (int j = 0; j < 40; j++) {
team[j] = array[j].substring(0, 3).trim();
info[j] = array[j].substring(3, 30).trim();
stats[j] = array[j].substring(36).trim();
}
// Random stuff i have been trying
System.out.println(team[1]);
System.out.println(info[1]);
System.out.println(stats[1]);
MyObject ob = new MyObject();
ob.setText(info[0]);
ob.setNumber(7, 23);
ob.setNumber(3, 456);
System.out.println("Text is " + ob.getText() + " and number 3 is " + ob.getNumber(7));
}
}
I'm pretty much stuck at this point because I am not sure how to add each teams score together.
This looks like homework... First of all you need to examine how you are parsing the strings in the file.
You're saying: the first 3 characters are the country, which looks correct, but then you set the info to the 4th through the 30th characters, which isn't correct. You need to dynamically figure out where that ends and the score begins. There is a space between the "info" and the "stats," knowing that you could use String's indexOf function. (http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf(int))
Have a look at Maps.
A map is a collection that allows you to get data associated with a key in a very short time.
You can create a Map where the key is a country name, with value being the total points.
example:
Map<String,Integer> totalScore = new HashMap<>();
if (totalScore.containsKey("COUNTRYNAME"))
totalScore.put("COUNTRYNAME", totalScore.get("COUNTRYNAME") + playerScore)
else
totalScore.put("COUNTRYNAME",0)
This will add to the country score if the score exists, otherwise it will create a new totalScore for a country initialized to 0.
Not tested, but should give you some ideas:
public static void main(String... args)
throws Exception {
class Structure implements Comparable<Structure> {
private String team;
private String name;
private Double score;
public Structure(String team, String name, Double score) {
this.team = team;
this.name = name;
this.score = score;
}
public String getTeam() {
return team;
}
public String getName() {
return name;
}
public Double getScore() {
return score;
}
#Override
public int compareTo(Structure o) {
return this.score.compareTo(o.score);
}
}
File file = new File("path to your file");
List<String> lines = Files.readAllLines(Paths.get(file.toURI()), StandardCharsets.UTF_8);
Pattern p = Pattern.compile("(\\d+(?:\\.\\d+))");
List<Structure> structures = new ArrayList<Structure>();
for (String line : lines) {
Matcher m = p.matcher(line);
while (m.find()) {
String number = m.group(1);
String text = line.substring(0, line.indexOf(number) - 1);
double d = Double.parseDouble(number);
String team = text.substring(0, 3);
String name = text.substring(3, text.length());
structures.add(new Structure(team, name, d));
}
}
Collections.sort(structures);
List<Structure> topFive = structures.subList(0, 5);
for (Structure structure : topFive) {
System.out.println("Team: " + structure.getTeam());
System.out.println("Name: " + structure.getName());
System.out.println("Score: " + structure.getScore());
}
}
Just remove <br> from your file.
Loading file into memory
Your string splitting logic looks fine.
Create a class like PlayerData. Create one instance of that class for each row and set all the three fields into that using setters.
Keep adding the PlayerData objects into an array list.
Accumulating
Loop through the arraylist and accumulate the team scores into a hashmap. Create a Map to accumulate the team scores by mapping teamCode to totalScore.
Always store row data in a custom object for each row. String[] for each column is not a good way of holding data in general.
Take a look in File Utils. After that you can extract the content from last space character using String Utils e removing the <br> using it as a key for a TreeMap. Than you can have your itens ordered.
List<String> lines = FileUtils.readLines(yourFile);
Map<String, String> ordered = new TreeMap<>();
for (String s : lines) {
String[] split = s.split(" ");
String name = split[0].trim();
String rate = splt[1].trim().substring(0, key.length - 4);
ordered.put(rate, name);
}
Collection<String> rates = ordered.values(); //names ordered by rate
Of course that you need to adjust the snippet.