Mapping all values to one key - java

Map<Object,String> mp=new HashMap<Object, String>();
Scanner sc=new Scanner(System.in);
System.out.println("Enter the instrument name");
String name=sc.next();
mp.put(name, "Control Valve");
mp.put(name, "BDV");
mp.put(name, "SDV");
mp.put(name, "ON-OFF VALVE");
mp.put(name,"Analyser");
Set s=mp.entrySet();
Iterator it=s.iterator();
while(it.hasNext())
{
Map.Entry m =(Map.Entry)it.next();
String key=(String)m.getKey();
String value=(String)m.getValue();
System.out.println("Instrument name :"+key+" fields:"+value);
}
}
}
In this only last value is mapped to the key .i.e analyser to key .
How to map all the values to one key entered by the user .And also it has to ask user to enter values for each value field.
updated code -:It asks for instrument name but then shows exception "java.util.ArrayList cannot be cast to java.lang.String"
Map<String,List<String>> mp=new HashMap<String,List<String>>();
Scanner sc=new Scanner(System.in);
System.out.println("Enter the instrument name");
String name=sc.next();
List<String> valList = new ArrayList<String>();
valList.add("Control Valve");
valList.add("BDV");
valList.add("SDV");
valList.add("ON-OFF VALVE");
valList.add("Analyser");
mp.put(name, valList);
Set s=mp.entrySet();
Iterator it=s.iterator();
while(it.hasNext())
{
Map.Entry m =(Map.Entry)it.next();
String key=(String)m.getKey();
String value=(String)m.getValue();
System.out.println("Instrument name :"+key+" fields:"+value);
}
}
}

I would suggest to use
Map<Object,List<String>> mp=new HashMap<Object, List<String>>();
So that you can maintain set of values to a given key.
if a list available for given key , get the list and add the new value to list.
UPDATED
Map<String,List<String>> mp=new HashMap<String,List<String>>();
Scanner sc=new Scanner(System.in);
System.out.println("Enter the instrument name");
String name=sc.next();
List<String> valList = new ArrayList<String>();
valList.add("Control Valve");
valList.add("BDV");
valList.add("SDV");
valList.add("ON-OFF VALVE");
valList.add("Analyser");
mp.put(name,valList);
for(String key : mp.keySet()){
System.out.print("Instrument name :"+key+" Values : ");
for(String val : mp.get(key)){
System.out.print(val+",");
}
}

I suspect you should be using a custom class with a field for each piece of information you need. This can be added once into the map for each name
public static void main(String... args) {
Map<String, MyType> mp = new LinkedHashMap<String, MyType>();
Scanner sc = new Scanner(System.in);
System.out.println("Enter the following comma separated with a blank line to stop.");
System.out.println("instrument name, Control Value, BDV, SDV, ON-OFF VALVE, Analyser");
for (String line; (line = sc.nextLine()).length() > 0; ) {
MyType mt = new MyType(line);
mp.put(mt.getName(), mt);
}
System.out.println("you entered");
for (MyType myType : mp.values()) {
System.out.println(myType);
}
}
static class MyType {
private final String name, controlValue, bdv, sdv, onOffValue, analyser;
MyType(String line) {
String[] parts = line.trim().split(" *, *");
name = parts[0];
controlValue = parts[1];
bdv = parts[2];
sdv = parts[3];
onOffValue = parts[4];
analyser = parts[5];
}
public String getName() {
return name;
}
public String getControlValue() {
return controlValue;
}
public String getBdv() {
return bdv;
}
public String getSdv() {
return sdv;
}
public String getOnOffValue() {
return onOffValue;
}
public String getAnalyser() {
return analyser;
}
#Override
public String toString() {
return "MyType{" +
"name='" + name + '\'' +
", controlValue='" + controlValue + '\'' +
", bdv='" + bdv + '\'' +
", sdv='" + sdv + '\'' +
", onOffValue='" + onOffValue + '\'' +
", analyser='" + analyser + '\'' +
'}';
}
}
if given the following input prints
Enter the following comma separated with a blank line to stop.
instrument name, Control Value, BDV, SDV, ON-OFF VALVE, Analyser
a,b,c,d,e,f
1,2,3,4,5,6
q,w,e,r,t,y
you entered
MyType{name='a', controlValue='b', bdv='c', sdv='d', onOffValue='e', analyser='f'}
MyType{name='1', controlValue='2', bdv='3', sdv='4', onOffValue='5', analyser='6'}
MyType{name='q', controlValue='w', bdv='e', sdv='r', onOffValue='t', analyser='y'}

You may need to use google guava multimap to achieve this.
A collection similar to a Map, but which may associate multiple values with a single key. If you call put(K, V) twice, with the same key but different values, the multimap contains mappings from the key to both values.
(or)
Change value as List and add all values which have same key to that list
Example:
List<String> valList = new ArrayList<String>();
valList.add(val1);
valList.add(val2);
mp.put(name, valList);

I would suggest looking at a Guava MultiMap
A collection similar to a Map, but which may associate multiple values
with a single key. If you call put(K, V) twice, with the same key but
different values, the multimap contains mappings from the key to both
values.
Otherwise you will have to implement a Map of Strings to some Java collection. That will work, but it's painful since you have to initialise the collection every time you enter a new key, and add to the collection if the empty collection exists for a key.

You may have a map of string array. Then you should retrive the array list and add new value.
Map<Object,ArrayList<String>> mp=new HashMap<Object, ArrayList<String>>();

Related

Input a name and a role and get an output of that role with the names

I need to do this for school. Its supposed to be a JAVA project.
So for example, if we give an input:
thomas teacher
charlie student
abe janitor
jenny teacher
The output will be:
teachers,thomas,jenny
students,charlie,
janitor,abe.
I am just a beginner so, so far I have this code:
`Scanner in = new Scanner(System.in);
String line = in.nextLine();
String[] words = line.split(" ");
//TreeMap treemap = new TreeMap();
ArrayList<String> admin = new ArrayList<String>();
Scanner input = new Scanner(System.in);
while(true){
Boolean s = input.nextLine().equals("Done");
//treemap.put(line, "admin");
if(words[1].contentEquals("admin")){
admin.add(words[0]);
}
else if(s == true){
break;
}
}
System.out.println("admins," + "," + admin);`
I was originally using a treemap but I don't know how to make it work so I thought of using an ArrayList and eliminating the brackets at the end.
EDIT:
So I now have the code:
HashMap<String, String> teacher = new HashMap<String, String>();
HashMap<String, String> student = new HashMap<String, String>();
HashMap<String, String> janitor = new HashMap<String, String>();
System.out.println("Enter a name followed by a role.");
Scanner in = new Scanner(System.in);
String line = in.nextLine();
Scanner name = new Scanner(System.in);
String r = name.nextLine();
while(true){
if(line.equals(r + " " + "teacher")){
teacher.put(r, "teacher");
}
}
I'll give you the hint because you should do it yourself.
Use a HashMap<String, List<String>> map and insert your inputs like below:
if(map.containsKey(words[1]))
{
List<String> list = map.get(words[1]);
list.add(words[0]);
map.put(words[1],list);
}
else
{
map.put(words[1],Arrays.asList(words[0]))
}
This way you will get list of names corresponding to each types(student/teacher) etc.
After that iterate over the map and print the list.
I think for a small amount of occupations it's reasonable to accomplish this using just array lists. I think the part you are having trouble with is the input structure so I'll help you out with an example of how to do that part and let you handle the filtering on your own:
private List<String> teachers = new ArrayList<>();
private List<String> students = new ArrayList<>();
private List<String> janitors = new ArrayList<>();
public void seperatePeople(){
Scanner in = new Scanner(System.in);
while(true){
//Keep getting the next line in an infinite loop
String line = in.nextLine();
if(line.equals("Done")){
break; //end the loop
}else{
//Split on the spaces
String[] personArray = line.split(" ");
//Remember each line is structured like : name, occupation
//So when we split the line the array list we get from it
//will be in the same order
putInArray(personArray[0], personArray[1]);
}
}
//Do whatever printing you have to do down here
}
private void putInArray(String name, String occupation) {
//filter and add to the correct list in here
}
If you wanted to implement this using a hashmap the input method would be the same, but instead of putting names into 3 pre-made occupation arraylists you create arraylists and put them inside a hashmap as you go:
private HashMap<String, List<String>> peopleHashMap = new HashMap<>();
public void seperatePeople(){
Scanner in = new Scanner(System.in);
while(true){
//Keep getting the next line in an infinite loop
String line = in.nextLine();
if(line.equals("Done")){
break; //end the loop
}else{
//Split on the spaces
String[] personArray = line.split(" ");
//Remember each line is structured like : name, occupation
//So when we split the line the array list we get from it
//will be in the same order
putInArray(personArray[0], personArray[1]);
}
}
//You can get all the keys that you created like this
List<String> keys = new ArrayList<>(peopleHashMap.keySet());
}
private void putInArray(String name, String occupation) {
if(peopleHashMap.containsKey(occupation)){
//If the key (occupation in this case) is already in the hashmap, that means that we previously
//made a list for that occupation, so we can just the name to that list
//We pull out a reference to the list
List<String> listOfNames = peopleHashMap.get(occupation);
//And then put the new name into that list
listOfNames.add(name);
}else{
//If the key isn't in the hashmap, then we need to make a new
//list for this occupation we haven't seen yet
List<String> listOfNames = new ArrayList<>();
//We then put the name into the new list we made
listOfNames.add(name);
//And then we put that new list with the into the hashmap with the occupation as the key
peopleHashMap.put(occupation, listOfNames);
}
}

How to retrieve word after specific word in Java?

I've this kind of String:
{aa=bbbb, cc=blabla1, ee=ffff, cc=blabla2, gg=hhhh, cc=blabla3,.......}
and i want to get a list of all words after cc=.
How can i do it? I'm not very confident with regex stuff.
public static void main(String[] args) {
String input = "aa=bbbb, cc=blabla1, ee=ffff, cc=blabla2, gg=hhhh, cc=blabla3";
String[] splitValues = input.split(", ");
Map<String,List<String>> results = new Hashtable<>();
List<String> valueList = null;
// iterate through each key=value adding to the results
for (String a : splitValues) {
// a = "aa=bbbb" etc
String[] keyValues = a.split("=");
// you can check if values exist. This assumes they do.
String key = keyValues[0];
String value = keyValues[1];
// if it is already in map, add to its value list
if (results.containsKey(key)) {
valueList = results.get(key);
valueList.add(value);
} else {
valueList = new ArrayList<>();
valueList.add(value);
results.put(key, valueList);
}
}
System.out.println("cc= values");
valueList = results.get("cc");
// assumes value is in results
for (String a : valueList)
System.out.println(a);
}
Your question is very vague but I am guessing the String is provided as is, like:
String toSearch = "{aa=bbbb, cc=blabla1, ee=ffff, cc=blabla2, gg=hhhh, cc=blabla3,.......}";
By list I am guessing you are referring to the abstract List object and not to an array. Here is a solution:
String toSearch = "{aa=bbbb, cc=blabla1, ee=ffff, cc=blabla2, gg=hhhh, cc=blabla3,.......}";
List<String> result = new ArrayList<String>();
int prevMatch = 0;
while (toSearch.indexOf("cc=", prevMatch+1) != -1) {
result.add(toSearch.substring( // Substring method.
toSearch.indexOf("cc=",prevMatch+1)+3,toSearch.indexOf(",") //Getting correct indexes.
));
prevMatch = toSearch.indexOf("cc=",prevMatch+1);
}
The prevMatch variable ensures that the indexOf("cc=") that will be returned will be the next one occurring in the String. For the above String the returning ArrayList will contain the words "blabla1","blabla2", "blabla3" and whatever else is encountered.

Receiving "null" in Place of Correct Values

I'm currently using Jersey REST to create a webpage that has a list of birds and taxonomy number, with a link to a page specifically about the bird in question. While my links work between the two pages, and my Bird Name and Taxonomy Number appear, I can't get the order or family name to appear. Following is the code in question.
#Path("/birdslist")
public class BirdsList extends Birds {
#GET
#Path("/all")
#Produces("text/html")
public String all() {
Iterator iterator = birdnames.keySet().iterator();
String page = "<html><title>All Birds</title><body>";
page += "<p>This is the list of all birds. <br> Click the taxonomy number of the bird you wish to view in detail.</p>";
while(iterator.hasNext()){
Object key = iterator.next();
String value = birdnames.get(key);
HashSet fam = family.get(key);
HashSet ord = order.get(key);
}
for (String key : birdnames.keySet()) {
page += String.format("<p>Name:%s <br> Taxonomy Number:<a href=%s>%s</a></p>",birdnames.get(key),key,
key);
getBird(key);
}
page += "</body></html>";
return page;
}
#GET
#Path("{key}")
#Produces("text/html")
public String getBird(#PathParam("key") String key) {
String page = "<html><title>Bird #: {key}</title><body>";
page += String.format("<p>This page contains info on the %s</p>",birdnames.get(key));
page += String.format("<p>Name:%s <br> Taxonomy Number:%s <br> Family:%s <br> Order:%s</p>",birdnames.get(key),key,family.get(key),order.get(key));
page += "<p>Please click <a href=all>here</a> to return to the list of all birds.</p>";
page += "</body></html>";
return page;
}
}
The family and order are saved in a HashSet that is inside of a hashmap, while bird name is in a hashmap. It was written over from a csv file and converted into hashmaps. Following is that code.
public class Birds {
HashMap<String,String> birdnames;
HashMap<String,HashSet<String>> family;
HashMap<String,HashSet<String>> order;
/**
Constructor reads the CSV of all birds
*/
public Birds() {
// long path to eBirds assuming Maven "mvn exec:java" is many levels up
String fileName = "src/main/java/com/example/rest/eBirds.csv";
boolean firstLine = true;
this.birdnames = new HashMap<String,String>();
this.family = new HashMap<String,HashSet<String>>();
this.order = new HashMap<String,HashSet<String>>();
try {
BufferedReader R = new BufferedReader(new FileReader(fileName));
String line;
while (true) {
line = R.readLine();
if (line == null) break;
if (firstLine) { // ignore the first line, it's not a bird
firstLine = false;
continue;
}
String[] fields = line.split(",");
if (!fields[1].equalsIgnoreCase("species")) continue; // ignore all but species records
birdnames.put(fields[0],fields[4]); // add this bird to name table
// extract the order name from fields[6]
String ordername = fields[6];
if (!order.containsKey(ordername)) { // if needed, create first-time order set
order.put(ordername,new HashSet<String>());
}
order.get(ordername).add(fields[0]); // new order member by number for lookup
// extract the family name from fields[7] -- removing quotes first if needed
String famname = fields[7].replace("\"","");
if (!family.containsKey(famname)) { // if needed, create first-time family set
family.put(famname,new HashSet<String>());
}
family.get(famname).add(fields[0]); // new family member by number for lookup
}
}
catch (IOException e) { System.out.println("Stack trace: " + e); }
}
...
}
I've never used HashSets before, that was part of the given info to us. Our assignment was to create a list page and pages specific to each bird and link between the two. I just can't get these last two values to appear correctly. Can anyone help?
Here you use the same key for all values, birdnames, family and order:
while(iterator.hasNext()){
Object key = iterator.next();
String value = birdnames.get(key);
HashSet fam = family.get(key);
HashSet ord = order.get(key);
}
But you initialize them with different keys:
// extract the order name from fields[6]
String ordername = fields[6];
if (!order.containsKey(ordername))
{ // if needed, create first-time order set
order.put(ordername, new HashSet<>());
}
order.get(ordername).add(fields[0]); // new order member by number for lookup
Here the key would be fields[6] and not the birdnames key.
If you want to keep using the same key, you could do the following for the orders:
if (!order.containsKey(fields[0]))
{
order.put(fields[0], new HashSet<>());
}
order.get(fields[0]).add(fields[6]);
Then you can use:
HashSet ord = order.get(key);
And you will receive all the orders for that bird name.
If you don't want to change that and still use the same key you could do something like the following, but that is highly discouraged as it destroys the purpose of using a map in the first place:
Set<String> ord = new HashSet<>();
for (String tmp : order.keySet())
{
if (order.get(tmp).contains(key))
ord.add(tmp);
}
Here ord would contain all the orders for the "key".
As you can see, you need to do much more redundant work, if you don't switch value and "key".

Java HashMap, One key multiple Values, One map

As the question reads.... and I do NOT want to use multiple maps, just one map.
My goal is to get a list of the names I enter in the input.
I have tried like a hundred different for-loops, but I always tend to end up with a list of the whole map and/or that the duplicate key is overridden.
import java.util.*;
public class Another {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String name;
HashMap<String, ToA>wordkey = new HashMap<String, ToA>();
ToA a = new ToA("Doolin", "Bill", "18580824-1464");
ToA b = new ToA("Dalton", "Bob", "18701005-2232");
ToA c = new ToA("James", "Jesse", "18470905-2401");
ToA d = new ToA("Dalton", "Emmet", "18710713-0818");
wordkey.put("Doolin", a);
wordkey.put("Dalton", b);
wordkey.put("James", c);
wordkey.put("Dalton", d);
System.out.println("Efternamn:");
name = scan.next();
}
}
public class ToA{
private String fname, lname, dob;
public ToA(String fname, String lname, String dob){
this.fname = fname;
this.lname = lname;
this.dob = dob;
}
public String getFname(){
return fname;
}
public String getLname(){
return lname;
}
public String getDob(){
return dob;
}
public String toString(){
return "\nFirstname: " + fname + "\nSurname: " + lname + "\nDateOfBirth: " + dob;
}
}
For inputting Dalton, I would like the output
Firstname: Bill
Surname: Dalton
DateOfBirth: 18701005-2232
Firstname: Emmet
Surname: Dalton
DateOfBirth: 18710713-0818
I'm really stuck with this so any help is highly appreciated, Thanks
To post my comment as an answer: use a Map<String, List<ToA>> like this:
Map<String, List<ToA>> wordkey = new HashMap<>();
ToA a = new ToA("Doolin", "Bill", "18580824-1464");
ToA b = new ToA("Dalton", "Bob", "18701005-2232");
ToA c = new ToA("James", "Jesse", "18470905-2401");
ToA d = new ToA("Dalton", "Emmet", "18710713-0818");
wordkey.put("Doolin", Arrays.asList(a));
wordkey.put("James", Arrays.asList(c));
wordkey.put("Dalton", Arrays.asList(b, d));
To print the names based on the input, you can do something like this:
System.out.println("Efternamn:");
name = scan.next();
List<ToA> toas = wordkey.get(name);
if (toas != null) {
System.out.println("ToAs");
for (ToA toa : toas) {
System.out.println("ToA: " + toa);
}
}
else {
System.out.println("No ToAs found for input: " + name);
}
There are several possibilities for what you are trying to achieve. A simple one would be to use Guavas Multimap or to use Apaches MultiMap.
Another possibility is to "wrap" the Map in a class and keep a List<ToA> as Value of the Map. You'd override the put, remove and get methods to what you need

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.

Categories

Resources