Need help sorting an ArrayList of strings by an in common substring
I'm trying to sort a .csv file, which I read into an ArrayList as strings. I would like to sort by the IP address within the string. Can someone please help me figure out the best way to sort these strings by a common substring each has, which is an IP address.
I'm pretty sure that I need to use Collections some how, but I don't know where to begin with them besides trying to look online for help. I had no luck finding any good examples, so I came here as a last resort.
Thanks for any help provided.
You need to write your own Comparator class. In the compare() method you substring out the two IP addresses, compare them and return appropriate value. Then you call Collections.sort() and pass your list and comparator.
Similar Messages
-
Need help Sorting an Arraylist of type Object by Name
Hey guys this is my first time posting on this forum so hopefully i do it the right way. My problem is that i am having difficulties sorting an Array list of my type object that i created. My class has fields for Name, ID, Hrs and Hrs worked. I need to sort this Array list in descending order according to name. Name is the last name only. I have used a bubble sort like this:
public static void BubbleSort(TStudent[] x){
TStudent temp = new TStudent();
boolean doMore = true;
while (doMore) {
doMore = false;
for (int i=0; i < x.length-1; i++) {
if (x.stuGetGPA() < x[i+1].stuGetGPA()) {
// exchange elements
temp = x[i]; x[i] = x[i+1];
x[i+1] = temp;
doMore = true;
before many time to sort an array of my class TStudent according to GPA. This time though i tried using an Array list instead of just a simple array and i can't figure out how i would modify that to perform the same task. Then i googled it and read about the Collections.sort function. The only problem there is that i know i have to make my own comparator but i can't figure out how to do that either. All of the examples of writing a comparator i could find were just using either String's or just simple Arrays of strings. I couldn't find a good example of using an Array list of an Object.
Anyways sorry for the long explanation and any help anyone could give me would be greatly appreciated. Thanks guys
Edited by: Brian13 on Oct 19, 2007 10:38 PMok still having problems I have this line of code to try and all Arrays.sort
Arrays.sort(Employee, TEmployee.FirstNameComparator);Then in my class TEmployee i have
public static Comparator FirstNameComparator = new Comparator() {
public int compare(Object employee, Object anotherEmployee) {
String lastName1 = ((TEmployee) employee).getEmpName().toUpperCase();
String lastName2 = ((TEmployee) anotherEmployee).getEmpName().toUpperCase();
return lastName1.compareTo(lastName2);
};Here is the rundown of what i have for this. I have 2 classes. One is called TEmployee and that class holds fields for Name, ID, Hrs Worked, Hourly Rate. Then i have another class called myCompany that holds an ArrayList of type TEmployee. Then i have my main program in a Jframe.
So maybe i am putting them in the wrong spots. The code in TEmployee thats make the comparator is fine. However when i try to call Arrays.sort from class myCompany i get this
cannot find symbol
symbol: method sort (java.util.Array list<TEmployee>.java.util.Comparator
location: class java.util.Arrays
I have to put the comparator in TEmployee right because thats where my fields for Name are? Do i call the arrays.sort from my main program or do i call that from the class myCompany where my ArrayList of TEmployees are stored?
Again guys thanks for any help you could give me and if you need any code to see what else is going on just let me know. -
i have a brand new MuVo n200
i need help, i put my cd's in and everyhting and i filled it with songs ans i can play them and everything, but i hate thats itssorted in ABC order. i cannot figure how to put them so it is in order by the CD or the bandname.
please help.
message me on aim if you want [email][email protected]][email protected][/url]To group the songs into albums or artist groups, I would definitely suggest putting all the tracks from each album/group in its own folder on your PC and put the folder on the muvo in just the same way as you would put a single mp3. The player (in normal play mode) will then play each folder all the way through before moving on to the next one alphabetically (or numerically, if you put numbers at the start of the folder names) and you can then use 'skip folder' to skip through to find the particular album or artist you're looking for. Play around with the shuffle modes too - you can shuffle within folders or just shuffle everything if you want.
Tracks will normally be played alphabetically. To get them to play in order of track number, put numbers at the beginning of each file name. E.g.: file 'examplesong.mp3' would become '0_ examplesong.mp3' If you've got tonnes of songs and you're worried about it taking ages, the computer will do it for you! Click on 'my computer', then click on 'Muvo N200 media explorer'.. This shows the contents of your player. Choose a folder to reorder the songs in and click on it to display the songs. In the pictures along the top of the window, 4th from the right is an icon with a downward facing arrow and an A above a Z. Click on this, it's called 'custom sort'. You can then use the arrows at the bottom to change the order of your tracks to how you want them. Click OK, and they'll all be numbered in that order!
For instructions on how to create folders in mediasource, read the thread in this link:
http://forums.creative.com/creativelabs/board/message?board.id=dap&message.id=926
I don't think you can put folders within folders in the muvo, but just the one layer really helps organisation.
Hope that helps!
x Flaneur
PS- scroll down in the thread in the link: Jeremy CL was nice enough to give pictures in his instructions! If you'd like more help, type 'create folders' or something into the forum search as there's probably quite a lot of advice kicking about here!Message Edited by flaneur on 03-27-2005 :8 PM -
I need to sort an array of strings based on the number in each string.
Basically, I have a directory of files that all have the same name but each with a different number on the end.
example: image 1.jpg, image 2.jpg, etc.
When I use the List Directory function that returns an array of strings containing the file names in the directory, they don't come out in a 1, 2, 3, order like they appear in the directory. It sorts them character by character so that they come out like: 1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 2, 20, 21, 22 etc.
Is there a simple way of sorting this array of strings with the file names (as above) so that they are in numerical order?It's a while since this thread was started, but I am sure others will have use for this so here goes:
The in-built array sort function sorts the strings the same way DOS and Windows do. Microsoft has fixed this in the Explorer that comes with XP, however the rest of the OS(s) still sorts the old way.
The attached "AlphaLogical String Array Sort" VIs will sort strings arrays the same way as the new XP Explorer. There are three different implementations of the sorting, one based on the Insertion sort algorithm, a Quick Sort based on recursive calls (the most elegant way, but unfortunately LabVIEW has too much overhead when doing recursive calls so this is actually a very slow alternative) and finally the fastest; a stack based Quick Sort. There is also a test VI that will show you how the different implementations perform.
I had not used recursive calls in LV much until I made the attached quick sort and was a bit disappointed by the fact that it is so slow, but it's a good learning example...The ability to do recursive calls this way was introduced in LV7 I believe...There is an example here on the zone that shows how you can calulate a factorial by using recursive calls, however - unlike for the quick sort (normally) - recursive calls are actually not the optimal solution for that calculation.
Message Edited by Mads on 09-13-2005 02:30 AM
MTO
Attachments:
AlphaLogical Sorting.zip 142 KB -
Need help sorting 2 arrays linked by their indexes
I have 2 arrays that have been linked by the index of both arrays. The first array has to be sorted alphabetically, so I need a way to sort the 2nd array so that the indices match up again with the first array.
Now, I cannot change my ArrayList (i.e. TreeSet, List, etc.) since there is lots of code that would have to be changed. Here is my test code. Hopefully everyone is a fan of the television show Friends so that you can see how if I sort the firstName Array alphabetically, then I have to have the 2nd array sorted to be "linked" back to the first array based on the index. I am looking for ideas, but if you have simple code, that would be great too.
import java.util.*;
public class Test
public static void main(String[] args)
System.out.println("BEGIN TEST...");
Test test = new Test();
test.beginTest();
System.out.println("\nTEST COMPLETE!");
public Test(){}
public void beginTest()
ArrayList firstName = new ArrayList();
ArrayList lastName = new ArrayList();
//Add to firstName ArrayList
firstName.add("Ross");
firstName.add("Chandler");
firstName.add("Rachel");
firstName.add("Phoebe");
firstName.add("Joey");
//Add to lastName ArrayList
lastName.add("Geller");
lastName.add("Bing");
lastName.add("Green");
lastName.add("Buffay");
lastName.add("Tribbiani");
try
System.out.println("TESTING...\n");
for(int index=0; index<firstName.size(); index++)
String first = firstName.get(index).toString();
String last = lastName.get(index).toString();
System.out.println("Hi, I am " + first + " " + last + ".");
catch(Exception X) { System.out.println("EXCEPTION! "+X); X.printStackTrace(); }
}Keeping the list in synch is conceptually easy.
Basically anything you do to the one List, you have to do to the other in order to keep them consistent.
How are you sorting your "firstnames" list?
Using the Collections.sort method, or some manual coding?
Would it be possible to change your datastructure from "parallel arrays" to "List of people objects"
iepublic class Person {
String firstName;
String lastName;
public Person(String firstName, String lastName){
this.firstName = firstName;
this.lastName = lastName;
// appropriate getter/setter methods
}Then you could build up your list like this:
List friends = new ArrayList();
friends.add(new Person("Ross", "Geller"));
friends.add(new Person("Chandler", "Bing"));
...Now when you sort the list, the last name always goes with the first name because they are in the same object.
You then write different Comparator objects to impose different orderings.
Hope this helps,
evnafets -
I need help sorting an Array.
Hi, I need to make a program that reads a string (sentence), then it counts the number of times each letter is "typed". As an optional challenge, the teacher told us to sort the results from the most repeated, to the least.
My program is working pretty well, here is the code:
import java.lang.String;
//import java.util.Collections;
//import java.util.*;
public class count {
final int alpha = 66;
int [] lower = new int [alpha];
* @param args
public static void main(String[] args) {
// TODO Auto-generated method stub
java.util.Scanner in = new java.util.Scanner (System.in);
char current;
final int alpha = 66;
int [] lower = new int [alpha];
int Spaces = 0;
System.out.println("Enter a sentence:");
String line = in.nextLine ();
//int length = line.length();
line = line.toLowerCase();
for (int ch = 0; ch < line.length(); ch++)
current = line.charAt(ch);
if (current >= 'a' && current <= 'z')
lower[current-'a']++;
else if (current == ' ')
Spaces ++;
System.out.println();
for (int letter=0; letter < lower.length;letter++)
if (lower[letter]>0){
System.out.print((char)(letter + 'a'));
System.out.println(": " + lower[letter]);
System.out.println ();
System.out.println ("Spaces: " + Spaces);
}[now, I want to sort the results. I tried using Arrays.sort(lower); but it doesnt work as it should. Example:
String: Hello
not sorted:
e: 1
h: 1
l: 2
o: 1
Spaces: 0
"sorted":
: 1
.:1
]:1
~:2
Spaces: 0
I would really appreciate your help.
Thanks, J. FlemmingSince you didn't post your Arraays.sort code, I can't
tell what you did wrong.
What does your array store? Element 0 is the number
of 'a' occurences, 1 is 'b', etc?
If so, then when you sort that, you'll have no idea
which element corresponds to 'a'. You'll need a
different approach for that. For instance, a class
that encapsulates two pieces of data: character and
number of occurences. You could then implement your
own sort, or learn how to use Comparable/Comparator.
Making Java
Objects Comparable
http://java.sun.com/docs/books/tutorial/collections/in
terfaces/order.html
http://www.javaworld.com/javaworld/jw-12-2002/jw-1227-
sort.htmlAs I said in my original post, I used Arrays.sort(lower), which is probably wrong. My Arrays does work as you described, element 0 is the numer of occurrences of 'a', and 1 is the number of occurrences of 'b' and so on. Thanks for your responce. Im looking into what you said. Thanks again.
Message was edited by:
Flemm.John -
SQL: Need help putting single quote around string
I want to put single quotes around string in my output.
I am running the following command as a test:
select ' ' hello ' ' from dual;
My expectation is to get 'hello' (Single quote around hello)
However I am getting the following error:
ERROR at line 1:
ORA-00923: FROM keyword not found where expected
When I do SHOW ALL at my SQL command prompt, the escape is set as follows:
escape "\" (hex 5c)
I even tried: select '\'hello\'' from dual;
I get back: select ''hello'' from dual
ERROR at line 1:
ORA-00923: FROM keyword not found where expectedHi,
user521525 wrote:
I want to put single quotes around string in my output.
I am running the following command as a test:
select ' ' hello ' ' from dual;
My expectation is to get 'hello' (Single quote around hello)You probably read that you can get a single-quote within a string literal by using two of them in a row.
That's true, but they really have to be in a row (no spaces in between), and you still need the single-quotes at the beiginning and end of the literal.
So what you want is
SELECT '''hello'''
FROM dual;Starting in Oracle 10, you can also use Q-notation, For example:
SELECT Q'['hello']'
FROM dual; -
Need help sorting /consolidating music. 3 external hard drives 25000+ songs
i have 3 external hard drives 1 terabite each. over 2000 complete albums. i may have 20 different folders or files of music spread over each drive. how do i clean up the music. example (folder a)has 700 albums and 1000 single songs by various artists, including 5 single copies of the song back in black by ac/dc. this folder includes 9 full ac/dc albums. (folder b) has 1500 albums and 2000 singles and has 14 ac/dc albums when i run (folder a) thru itunes and it completes and all music data shows. i then will run (folder b) thru i tunes, but i do not want 9 ac/dc back in black singles off the album back in black, nor do i want 2 complete back in black albums, 2 highway to **** albums and so forth, i want itunes to only install the 5 albums that are not in (folder a). please help.
Welcome to the Apple discussions.
You may want to consider posting this question in the iTunes discussion area at http://discussions.apple.com/category.jspa?categoryID=149
It sounds like you don't currently back up your hard drive, and if your iTunes library is that important to you, you should figure out how to back it up now. Easiest way is to buy an external drive larger than your existing internal hard drive, get a program like SuperDuper, which is what I use, and copy your drive to the external backup. Then you can point iTunes to it to use the library there. SuperDuper can be found at http://www.shirt-pocket.com/SuperDuper/SuperDuperDescription.html
I prefer an external hard drive with a firewire connection, so I can boot from it if need be (a Powerbook can't boot from a USB device). If you do get an external hard drive with only a USB connection, then it would be good for it to have it's own power supply since some drives can't get enough power from the Powerbook USB to start or work properly. -
I need help parsing a swift data string
i need to parse swift financial data
is there a way to use split or stringtokenizer for ::
and keep the :: as part of the new seperated data.
i want to put each string starting with :: on a seperate line in a text box.
i gave up and tried it with a loop and a stringbuffer , and indexof.
if (line.indexOf("::") == Strpos ){
frame.jTextArea1.append(displayline.toString());
displayline = new StringBuffer();
displayline.append(line.substring(Strpos, (Strpos + 2)));
Strpos += 2;
if (line.indexOf("::") != Strpos ) {
displayline.append(line.substring(Strpos, Strpos + 1));
System.out.println( displayline);
Strpos++;
but i cant get that to work either.
if anyone knows how to parse swift data please give me your email address.
i've been doing it in cobol for 15 yrs and i just cant get the cobol techniques to translate to java.
thanks.as i said
i am really a cobol guy
and yes as you see i did try to use indexof in my code.
but there must be something about indexof that i'm not getting.
it works the first time in the loop but then as i increment my start position(strpos)
the indsex of no longer works.
am i using the correct technique to increment the start position thru the string buffer.
thanks guys. -
I need help. (format for DB Connect String and Parameters)
I do not understand the DB Connect String
or the Other Parameters
in the DB Connect String whats the format
Can someone point to some help for using
the Oracle Reports Paper Report TesterHello,
DB Connect String : Like for other tools (SQL*Plus / ..; ) provide a string like
user/password@dbalias
Other parameters : if you have created parameters in your Reports, you can specify their value here.
Example : a parameter P_PARAM is defined in your Reports, you can set the value of "Other parameters" :
P_PARAM=my_value
Regards -
I need help converting date interger in string.
I am a beginner if you can even say that..... But to the point I'm using Dreamweaver and I'm pulling data from my database and it's being displayed on my webpage. Currently the code below pulls the month from the database as a number. I would like it to pull the date and change it from a number to it corresponding abbreviated month. ( ie. if it pulls 12-01-11 I need the 12 to be displayed as DEC on my website.) any help is much appreciated.
<?php echo $row_frt_summary['month']; ?>You can do it either in SQL or PHP,
For MySQL, use the date_format function with the %b specifier: http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_date-format
For PHP, use date_fomat with the M format character: http://www.php.net/manual/en/function.date-format.php
Also, PHP, SQL and application development questions should be posted in the app dev forum. -
Newbie needs help sorting out a publishing error message!
I'm just learning this stuff, and I got the following message when I tried to publish my website.
Can’t create the file “shapeimage1_link0.png.” The disk may be damaged, full, or you may not have sufficient access privileges.
I previously published with no problems, after re-editing my sight, I ran into this problem. I'm rather incompetent at this stuff. Help much appreciated!Two points that may help some one help me...
Does this part of the error message
'shapeimage1_link0.png.' mean that some specific
image on my site is causing the problem. If I could
find and delete that would it help? How would I find
which image has that tag?
Hello Pete,
i have been having the same difficulties. I was able to publish last week, but not this week. I followed many of the same procedures that people have been recommending (thanks for all the helpful suggestions), but I still get the same error message. I have a feeling that it is related to an issue with the new OS update and/or with the new iWeb update. I even deleted the new blog entry and went back to iWeb 1.1.1 and I could not get it to publish (thus, I had the same exact conditions that I had last week when I could get it to publish except for now I have OS 10.4.8 instead of 10.4.7).
I am at a loss on what to try. i get the same exact error message as you do, no matter whether I publish to a folder or to .mac. I can see that almost everything gets published except it gets hung up at creating that 'shapeimage1_link0.png' file. I wish I could find a way to figure out how to have iWeb not create that file.
I also tried to create a whole new site with the old content and still got the same error message.
I hope that we can get this problem solved soon (I really think Apple needs to provide a fix). I am starting to look at other programs, just so I can update my existing page. Macromedia Contribute allows me to fix parts of my existing (on the server) website. They have a free 30 day demo. I may have to purchase the program if Apple doesn't fix the problem soon.
Good luck and I will let you know whether I find a fix. -
Need help on converting milliseconds to string.
Hi,
I am really confused by GMT. I need to convert milliseconds to string. A millisecond represents the date of 2/14/02 22:37:27 GMT. I formatted the string so that output is in the right format. But I kept getting a time string of "02/14/02 16:37:27". How do I get a string of "02/14/02 22:37:27" instead? My local time zone is GMT-6.
Thank you very much.Is it a Calendar object you are using? If so it look slike there is a method called setTimeZone(). Its clear by your output that you are getting a local time for your zone so you just need to change the zone for that particular Calendar object (I think I never tried it)
-
Need help with if statements involving strings.
For this code, assume that I input a value that would make the boolean statement true. For some reason, this program will never return true. Can somebody please help me?
Scanner scan = new Scanner(System.in);
String personPlay;
boolean loop=false;
System.out.print("Enter a proper string(RPS): ");
personPlay=scan.nextLine();
if (personPlay=="R"||personPlay=="P"||personPlay=="S")
loop=true;Don't use == to compare Strings. use .equals
if(personPlay.equals("R") || personPlay.equals("P") || personPlay.equals("S"))
loop = true;
} -
Need help Sorting a Hashtable using values??
I have a hastable whose keys are unique but values are not. The problem is that i have to sort the hashtable by values.
You can't really sort a Hashtable by values, at least not directly. What you probably want is a way to be able to iterate through all the values contained in the Hashtable in a way that is consistent with some order defined on those values. An easy way to do this goes as follows:
Map m; // let that be your Hashtable
List vals = new ArrayList(m.values());
Collections.sort(vals); // uses the values natural order OR
Collections.sort(vals, my_comparator); // uses the order defined by my_comparator
// this will iterate in the order defined on the values
Iterator it = vals.iterator();
while(it.hasNext()) {
Object val = it.next();
}
Maybe you are looking for
-
How to backup more than one database using powershell
I am Trying to backup more than one database using the following script but no luck. I want user to type on command line the database they want to backup, e.g all databases that have "test" at the front like test.inventory, test.sales so i want user
-
it is infuriating that the US itunes store has all the tv shows i want but cannot buy them in the uk i.e. csi ncis other networks have realised and are releasing new series simultaneously in uk and US. i.e. castle surely cbs must comprehend if they c
-
Getting an error from calling a store proc
this is my code calling a store proc. i got all oracle 8i drivers imported. package FMISBean; import java.sql.*; import oracle.jdbc.driver.*; public class getrecordj public static void main(String [] args){ //global variables Conn
-
I get CDD-22400 but there is no external reference.
Hi, This message is related to the one I posted last week "Check constraint or database trigger disappear + Dr Watson". I work with Designer 9i (9.0.2.5) under NT4 SP6 and with db 9.2.0.3. I have more details and I can reproduce the behaviour. Here i
-
Moving from Bridge to Lightroom. Will metadata in existing files be recognized by Lightroom, and should I select embed+sidecar when adding files to library for the first time.