Trying to figure out Big 0 notations for my program - java

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.

Related

I want to data type Conversion in a row in android

Hi.
I'm making an app that receives data from bluetooth by using stringbuilder
And makes it slice for using another activity.
The image shows what i want to make.
Q1. What should i use c->d, d->e ?
Q2. There will be a lot of data, I want to know the way to simplify this sequence
******************** edited ********************
I have practiced by adding value to Arraylist.
But in String Array, there is no .get(), so i couldn't access to element's length.
public static ArrayList<String> randomValue = new ArrayList<>();
public static int iDistance=0, xIAngle=0, yIAngle=0, zIAngle=0;
public static String distance, xAngle, yAngle, zAngle;
randomValue.add("12345090080070");
randomValue.add("15640080085071");
randomValue.add("16542070084074");
randomValue.add("12645080087078");
randomValue.add("21345084081060");
randomValue.add("14785078075065");
randomValue.add("13155079077077");
randomValue.add("14623080078078");
randomValue.add("14918086080078");
randomValue.add("15684085082080");
for (int i=0; i<randomValue.size(); i++){
String a = randomValue.get(i);
String distance = a.substring(0,5);
String xAngle = a.substring(5,8);
String yAngle = a.substring(8,11);
String zAngle = a.substring(11,14);
//String to int
iDistance = Integer.parseInt(distance);
xIAngle = Integer.parseInt(xAngle);
yIAngle = Integer.parseInt(yAngle);
zIAngle = Integer.parseInt(zAngle);
}
It seems like you are just stuck on finding the equivalent of get for a string array. To access an element in an array, the syntax is array[I], so if you were using a string array, this line:
String a = randomValue.get(i);
would have been:
String a = randomValue[i];
The code for your sequence of transformations can be shortened with Streams:
// this is the sequence of transformation starting with the sting builder "a"
List<String> randomValueWithLength14 =
Arrays.stream(a.toString().split(";")).filter(x -> x.length() == 14)
.collect(Collectors.toList());
// this is the for loop shown in your code
for (int i=0; i<randomValueWithLength14.size(); i++){
String s = randomValueWithLength14.get(i);
String distance = a.substring(0,5);
String xAngle = s.substring(5,8);
String yAngle = s.substring(8,11);
String zAngle = s.substring(11,14);
//String to int
iDistance = Integer.parseInt(distance);
xIAngle = Integer.parseInt(xAngle);
yIAngle = Integer.parseInt(yAngle);
zIAngle = Integer.parseInt(zAngle);
}

Parsing input from file, delimiters, loops, java

The overall project is creating a system manager for airports. It keeps track of airports, flights, seating sections, seats and other relevent info for each of those catagories. The initial system is set up by importing from a file that's formatted a certain way. I'm having problems parsing the file properly to set up the initial system. the data is parsed from the file and used as method parameters to create the objects: Airport, Airline, Flight, FlightSection, and Seat.
the formatting is:
[list-of-airport-codes] {list-of-airlines}
list-of-airport-codes ::= comma-separated strings
list-of-airlines ::= airline-name1[flightinfo-list1], airline-name2[flightinfo-list2], airlinename3[flightinfo-list3], …
flightinfo-list ::= flightID1|flightdate1|originAirportCode1|destinationAirportCode1[flightsectionlist1], flightID2|flightdate2|originAirportCode2|destinationAirportCode2[flightsection-list2], …
flightdate ::= year, month, day-of-month, hours, minutes
flightsection-list ::= sectionclass: seat-price: layout: number-of-rows, …
sectionclass ::= F, B, E (for first class, business class, economy class)
layout ::= S, M, W (different known seating layouts)
example:
[DEN,NYC,SEA,LAX]{AMER[AA1|2018,10,8,16,30|DEN|LAX[E:200:S:4,F:500:S:2],
AA2|2018,8,9,7,30|LAX|DEN[E:200:S:5,F:500:S:3], …], UNTD[UA21|2018,11,8,12,30|NYC|SEA[E:300:S:6,F:800:S:3], UA12|2018,8,9,7,30|SEA|DEN[B:700:S:5, F:1200:S:2], …], FRONT[…], USAIR[…]}
I tried brute forcing it using a combination of delimiters and while loops. The code successfully creates the Airports, first Airline and Flighsections, but when it gets to creating the second airline it crashes, because i'm not looping properly, and having a hard time getting it right. My code for it as of now, is a mess, and if you're willing to look at it, I would appreciate any constructive input. My question is what would be a better way to approach this? A different design approach? Maybe a smarter way to use the delimiters?
Thanks in advance for your help!!
here's what i've tried.
private void readFile(File file){
System.out.println("reading file");
Scanner tempScan;
String result;
String temp = "";
scan.useDelimiter("\\[|\\{");
try{
// AIRPORTS
result = scan.next();
tempScan = new Scanner(result);
tempScan.useDelimiter(",|\\]");
while(tempScan.hasNext()){
temp = tempScan.next();
sysMan.createAirport(temp);
}
tempScan.close();
/* AIRLINE
* FLIGHT
* FLIGHTSECTION
*/
do{
// AIRLINE (loop<flight & fsection>)
result = scan.next();
sysMan.createAirline(result);
// FLIGHT
result = scan.next();
tempScan = new Scanner(result);
do{
tempScan.useDelimiter(",|\\|");
ArrayList flightInfo = new ArrayList();
while(tempScan.hasNext()){
if(tempScan.hasNextInt()){
flightInfo.add(tempScan.nextInt());
} else {
flightInfo.add(tempScan.next());
}
}
tempScan.close();
sysMan.createFlight(sysMan.getLastAddedAirline(),(String)flightInfo.get(0), (int)flightInfo.get(1), (int)flightInfo.get(2), (int)flightInfo.get(3), (int)flightInfo.get(4), (int)flightInfo.get(5), (String)flightInfo.get(6), (String)flightInfo.get(7));
// FLIGHTSECTION (loop<itself>)
result = scan.next();
tempScan = new Scanner(result);
tempScan.useDelimiter(",|:|\\]");
ArrayList sectInfo = new ArrayList();
int i = 1;
while(!temp.contains("|")){
if(tempScan.hasNextInt()){
sectInfo.add(tempScan.nextInt());
} else {
temp = tempScan.next();
if(temp.equals(""))
break;
char c = temp.charAt(0);
sectInfo.add(c);
}
if(i == 4){
sysMan.createSection(sysMan.getLastAddedAirline(), sysMan.getLastAddedFlightID(), (char)sectInfo.get(0), (int)sectInfo.get(1), (char)sectInfo.get(2), (int)sectInfo.get(3));
i = 1;
sectInfo = null;
sectInfo = new ArrayList();
continue;
}
i++;
}
}while(!temp.equals("\\s+"));
}while(!temp.contains("\\s+"));
}catch(NullPointerException e){
System.err.println(e);
}
}
I'd rather chunk it down by regexp mathing the outer bounds, have a look, I took it a couple of levels broken.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Tokeni {
static String yolo = "[DEN,NYC,SEA,LAX]{AMER["
+ "AA1|2018,10,8,16,30|DEN|LAX[E:200:S:4,F:500:S:2],"
+ "AA2|2018,8,9,7,30|LAX|DEN[E:200:S:5,F:500:S:3]],"
+ "UNTD[UA21|2018,11,8,12,30|NYC|SEA[E:300:S:6,F:800:S:3],"
+ "UA12|2018,8,9,7,30|SEA|DEN[B:700:S:5, F:1200:S:2]]}";
public static void main(String[] args) {
Matcher airportCodesMatcher = Pattern.compile("\\[(.*?)\\]").matcher(yolo);
airportCodesMatcher.find();
String[] airportCodes = airportCodesMatcher.group(1).split(",");
Matcher airLinesMatcher = Pattern.compile("\\{(.*?)\\}").matcher(yolo);
airLinesMatcher.find();
String airLinesStr = airLinesMatcher.group(1);
System.out.println(airLinesStr);
Pattern airLinePattern = Pattern.compile("\\D+\\[(.*?)\\]\\]");
Matcher airLineMatcher = airLinePattern.matcher(airLinesStr);
while( airLineMatcher.find() ) {
String airLineStr = airLineMatcher.group(0).trim();
if(airLineStr.startsWith(",")) {
airLineStr = airLineStr.substring(1, airLineStr.length()).trim();
}
System.out.println(airLineStr);
Matcher airLineNameMatcher = Pattern.compile("[A-Z]+").matcher(airLineStr);
airLineNameMatcher.find();
String airLineName = airLineNameMatcher.group(0).trim();
System.out.println(airLineName);
airLineStr = airLineStr.substring(airLineStr.indexOf("[")+1, airLineStr.length());
Matcher airLineInfoMatcher = Pattern.compile("\\D+(.*?)\\]").matcher(airLineStr);
while(airLineInfoMatcher.find()) {
String airLineInfoStr = airLineInfoMatcher.group(0).trim();
if(airLineInfoStr.startsWith(",")) {
airLineInfoStr = airLineInfoStr.substring(1, airLineInfoStr.length()).trim();
}
System.out.println(airLineInfoStr);
}
}
}
}

manipulate and sort text file

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.

Java - Improving iteration through large String List

I have to parse files which has around 50000 lines and has to iterate through each line, parse, create a List and save to database. Initially I thought the time taken is because of reading the file. But the file is actually read within a second. But the parsing of data takes long time.
public static final String record = "dlrCode,partNumber,5,0.00,5000.00,0.00,0,0.00,0,0.00,0,0.00,0,0.00,0,0.00,0,0.00,0,0.00,0,0.00,0,0.00,0,0.00,0,0.00,0,0.00,0,0.00,0,0.00,0,0.00,0,0.00,0,0.00,0,0.00,0,0.00,0,0.00,0,0.00,0,0.00,0,0.00,0";
public static final String COMMA = ",";
public static final String QUOTES = "\"";
public static final String EMPTY_STRING = "";
public static void main(String[] args){
List<String> recordsList = new ArrayList<String>();
Date time = new Date();
Part partVO = null;
PartHistory partHistoryVO = null;
List<PartHistory> partHistoryList = null;
List<Part> partsList = new ArrayList<Part>();
int splitLength = 0;
Calendar cal = Calendar.getInstance();
int historySplitCount = 0;
int monthCountReverse = 0;
//add 20000 records to list
for(int i=0; i<20000; i++){
recordsList.add(record);
}
System.out.println("Added in "+((new Date()).getTime() - time.getTime()) +" ms");
//reset time
time = new Date();
//parse records
for(String sCurrentLine : recordsList){
partVO = new Part();
partHistoryList = new ArrayList<PartHistory>();
//Parsing inventory information
partVO.setDealerCode(sCurrentLine.split(COMMA)[0]);
partVO.setPartNumber(sCurrentLine.split(COMMA)[1]);
partVO.setDmsMfId(sCurrentLine.split(COMMA)[2]);
partVO.setQtyOnHand(Math.round(Float.parseFloat(sCurrentLine.split(COMMA)[3])));
partVO.setDealerNet(Float.parseFloat(sCurrentLine.split(COMMA)[4]));
//Parsing history information
//starting from the 6th record as the first 5 records are used above
historySplitCount = 5;
//to subtract one month from current date
monthCountReverse = -1;
splitLength = sCurrentLine.split(COMMA).length;
while(splitLength>=(historySplitCount+1)){
partHistoryVO = new PartHistory();
//subtract one month from current date
cal.add(Calendar.MONTH, monthCountReverse);
partHistoryVO.setMonth(cal.get(Calendar.MONTH)+1);
partHistoryVO.setYear(cal.get(Calendar.YEAR));
partHistoryVO.setLineHitsMonthly(Math.round(Float.parseFloat(sCurrentLine.split(COMMA)[historySplitCount])));
historySplitCount++;
partHistoryVO.setQuantity(Math.round(Float.parseFloat(sCurrentLine.split(COMMA)[historySplitCount])));
historySplitCount++;
partHistoryList.add(partHistoryVO);
}
partVO.setHistoryList(partHistoryList);
partsList.add(partVO);
}
System.out.println("Iterated in "+((new Date()).getTime() - time.getTime()) +" ms");
}
Output
Added in 15 ms
Iterated in 12823 ms
Can the iteration time be improved and brought under atleast 5 seconds?
You're calling
sCurrentLine.split(COMMA)
several times in your code. Make a
final String[]
variable the first time you call it in the loop and use that instead thereafter and it'll get that many times faster.
For each line, you call the split() function multiple times, sCurrentLine.split(COMMA)[0],
a better way is to split it once and store into an array
String[] elements = sCurrentLine.split(COMMA);
dealerCode = elements[0];
partNumber = elements[1];
FYI, to count how much time spent, you can also use System.currentTimeMillis(), this does not need to create a new Date instance :)
long timeStarts = System.currentTimeMillis();
//loop goes here
long timeTook = System.currentTimeMillis() - timeStarts;

How to group the sorting of a file?

I'm trying to sort delimited files with a Time stamp | level | sensor name | measurement value structure so that all data associated with the sensor having the smallest time stamp would first be listed in increasing timestamp, then all the data associated with the sensor having the second smallest time stamp would be listed in increasing timestamp, etc…
Here’s an example of delimited file to be sorted :
20140102073500|1|sensor5|0.188|
20140102073502|1|sensor2|0.193|
20140102073600|2|sensor5|0.577|
20140102073603|2|sensor2|0.585|
20140102073700|3|sensor5|1.207|
20140102073702|3|sensor2|1.183|
Here what I want :
20140102073500|1|sensor5|0.188|
20140102073600|2|sensor5|0.577|
20140102073700|3|sensor5|1.207|
20140102073502|1|sensor2|0.193|
20140102073603|2|sensor2|0.585|
20140102073702|3|sensor2|1.183|
(note that I cannot sort by "sensor name / time stamp" because the sensor with the smallest time stamp changes from one file to the other...)
Here the coding I’m trying to work from (which only sort in ascending time stamp) :
import java.io.*;
import java.util.*;
public class Sort8 {
public static void main(String[] args) throws Exception {
Map<String, String> map;
try (BufferedReader reader = new BufferedReader(new FileReader("C:\\Test\\test.txt"))) {
map = new TreeMap<>();
String line;
while((line=reader.readLine())!=null){
map.put(getField(line),line);
System.out.println(getField(line));
}
System.out.println(map.values());
}
try (FileWriter writer = new FileWriter("C:\\Test\\test_sorted.txt")) {
for(String val : map.values()){
// System.out.println(val);
writer.write(val) ;
writer.write("\r\n");
}
}
}
private static String getField(String line) {
return ((line.split("\\|")[1])+(line.split("\\|")[3]));
}
}
I'm new to Java so thank in advance for the help you can provide !
Put a comparator in the construction of your tree map.
map = new TreeMap<>(new Comparator<String>() {
#Override
public int compare(String s1, String s2) {
String[] a1 = s1.split("|");
String[] a2 = s2.split("|");
// First compare sensor
int sensor1 = Integer.parseInt(a1[2].replace("sensor", ""));
int sensor2 = Integer.parseInt(a2[2].replace("sensor", ""));
if(sensor1 != sensor2) {
return Integer.valueOf(sensor1).compareTo(sensor2);
}
// Second compare timestamp
long time1 = Long.parseLong(a1[0]);
long time2 = Long.parseLong(a2[0]);
return Long.valueOf(time1).compareTo(time2);
}
});

Categories

Resources