Comparable? sorting Question

Hello,
I am new and I am stumbling pretty good with the sorting capabilities in Java.
I have a textfile which looks like this:
Scott Purcell
Doug Storms
Diane Purcell
Kelly Storms
I want to open that textfile up (that is easy) and somehow sort the list by lastname and if they are equal, head and sort on the first name.
I asked yesterday, but got no good answers except to use comparable and create a new class?
Anyway, I was hoping someone could take some time out of their busy schedule and possibly assist me in accomplishing this task?
Thanks,
Scott

Here's a start:
class Person implements Comparable {
    // store the data for the first and last name
    // implement the method for Comparable
}Now all you have to do is complete the class and the rest of the program. Try reading the API docs at http://java.sun.com/docs/ for more help with sorting.

Similar Messages

  • Sorting question over state...

    Hi there,
    Anyone know where you amend the over state / hover of an option in a sorting question ???
    Been looking in the object style manager but can't find it in there...
    Thanks in advance...

    You are talking about the partially transparent grey bar that appears when hovering over an answer in the Sequence type of questions. There is no style that can be customized AFAIK. It is not even changing with the included themes. Same is valid for the connecting lines in matching questions that are always black, color cannot be changed for them neither. It is a pity, would recommend you enter a feature request to be able to customize the color of both the hover bar and those lines.
    https://www.adobe.com/cfusion/mmform/index.cfm?name=wishform
    Lilybiri

  • Collections.sort question

    Hi,
    This is my question. I have the following classes
    class A {
         int num = 1;
    class B extends A implements Comparable<B>{
       int count = 0;
       public int compareTo(B b) {
            return count - b.getCount;  
      public void setCount(int count) {
            this.count = count;
      public int getCount() {
             return count;
    }After i put the a couple of the B classes (after setting count) in a LinkedList of type A, i get a problem trying to sort them. The compiler gives me a variable Collections error on the Collections.sort
    Any ideas on how to solve this would be appreciated.
    Thanks

    Are you talking about this A* algorithm? (I've never heard of it before.)
    http://en.wikipedia.org/wiki/A-star_search_algorithm
    The code you have with the "instanceof" test might work. Not sure what the goal is, or how the algorithm works (I didn't read the above link in detail), so I can't say for sure whether it will "work" for what you are doing. Once you sort the "B" objects, what do you need to do with that sublist (i.e., with the bList in your code)?
    I've never used generics, so I don't know much about them. Is it possible to make "A" Comparable, giving a dummy implementation to compareTo (i.e., maybe even just make it always return '0' [all values are equal]), and then have "B" implement Comparable such that B's compareTo will override A's version? I don't know if it is possible (or even desirable)--just a thought.

  • Is it possible to create exception rule in Comparator sort order?

    I have been working on trying to learn how to use Comparators to sort Collections... In one of my recent experiments, I tried to order a PriorityQueue of String elements alphabetically, in ascending order, with one exception: any word beginning with the letter "z" should be given a higher priority than any other word. I haven't been able to find a way to do this, nor to discern whether or not it's possible.
    Any help is appreciated.

    Try something like this:public class MyComparator implements Comparator<String> {
        @Override
        public int compare(String s1, String s2) {
            boolean s1StartsWithZ = s1.startsWith("z");
            boolean s2StartsWithZ = s2.startsWith("z");
            if (s1StartsWithZ && !s2StartsWithZ) return 1;
            if (s2StartsWithZ && !s1StartsWithZ) return -1;
            return s1.compareTo(s2);
    }

  • Sorting question xsl

    hi,
    I am sorting a list by category, but now I know that one of the categories should go to the bottom of the list when displayed.
    I tried concatenating some value to it so it would go to the bottom, but it's not working correctly. Any other ideas to achieve this?
    mhoran

    You are talking about the partially transparent grey bar that appears when hovering over an answer in the Sequence type of questions. There is no style that can be customized AFAIK. It is not even changing with the included themes. Same is valid for the connecting lines in matching questions that are always black, color cannot be changed for them neither. It is a pity, would recommend you enter a feature request to be able to customize the color of both the hover bar and those lines.
    https://www.adobe.com/cfusion/mmform/index.cfm?name=wishform
    Lilybiri

  • Urgent array sorting question

    I've sorted an array with "Collections.sort(myArrayList)" ..that's ok..but
    in my JList words appare sorted first the uppercase after lowercase
    (i.e. A,CCC,DDDDD,aa,bbb,cc,d)......I want it sort together..
    A lot of thanks for all answer!!

    Use Collections.sort(List list, Comparator c) api.
    Look into java.util.Comparator to create your own custom comparator, for ex.
    public class StringIgnoreCaseComparator implements Comparator {
      public int compare(Object o1, Object o2) {
        String s1 = (String)o1.toLowerCase();
        String s2 = (String)o2.toLowerCase();
        return s1.compareTo(s2);
      public boolean equals(Object obj) {
    }--lichu                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Playlist name sorting question

    First off, sorry if this has been discussed before, I couldn't find it anywhere.
    My question is, is there any way to sort my playlists via a "Sort Name" option or something so that a playlist starting with 'the' (for example, "The Letter Black") will be sorted, in the case of the example, under 'L' instead of 'T'? Thanks in advance.
    Blessings.

    Sorry, there are no controls about the sort order of playlists. They go folders, smart playlists, and regular playlists, with a lexical sort in each.
    However, you don't need to create playlists for individual artists and albums. You can easily get to them by the column browser. To turn it on, click View > Column Browser > Show. Then type "lett" in the search bar and you will be right there.

  • Another Sorting Question!

    Ok, I already asked something like this, but I was unsure about what to do.
    But now I know.
    I want to create a linked list of items. each item has a String and an int.
    in a different class, i want to create a linked list of these items, inserted in random order.
    what i want to do is sort the list alphabetically by the String.
    package political;
    import java.util.Comparator;
    public class Item {
         String s, state;
         int p, people;
         public Item (String s, int p)
              people = p; state = s;
         public String name ()
         {return state;}
         public void printer () {System.out.println(state + " "+ people);}
    }

    You mean you don't understand the arithmetic involved in dividing a given number into given ratios? Or the details of how the US electoral votes in particular are determined?
    The latter will be described at Wikipedia I would guess.
    The former is straightfoward. Suppose there were just three states with populations given by A: 100 B: 200 C:500 and you wanted to share 10 votes between them.
    First determine the proportion of the entire population (100+200+500=800) that each state has. A: 100/800=0.125, B: 200/800=0.25 C:500/800=0.625.
    Then multiply these by the number of votes to be shared. A: 0.125*10=1.25, B: 0.25*10=2.5, C: 0.625*10=6.25
    So A gets 1 vote, B gets 2 votes and C gets 6 votes.
    The problem is that there is one vote left over. I seem to recall reading years ago (when I was a student - over half a life time ago!) that the US has used different strategies at different times. To suit whoever could best stack the electoral authorities. You could argue that B gets the extra vote (because B's "left over" 0.5 is biggest) or that C should have it (because C's "left over" represents the largest number of people 0.25*500=125). Or you could come up with other algorithms. As I said Wikipedia is sure to document the currently used process.
    Edited by: pbrockway2 on Jan 11, 2008 7:32 PM
    This page has details:
    http://en.wikipedia.org/wiki/United_States_Electoral_College
    In fact the number of votes is determined by the number of Representatives and Senators each state has in the US Congress (except for DC which rides a bicycle).
    It's the House of Representatives that is fixed in size (currently 435) dished out in proportion to the decennial census count. I can't find any details about the exact allocation of the "left over" representatives, the details of the process are apparently specified by the Reapportionment Act of 1929 and the Apportionment Act of 1941.
    http://en.wikipedia.org/wiki/United_States_House_of_Representatives
    http://en.wikipedia.org/wiki/Size_of_the_U.S._House_of_Representatives
    Edited by: pbrockway2 on Jan 11, 2008 8:04 PM
    There is a discussion of the apportionment problem beginning on page 32 here:
    http://www.maths.sussex.ac.uk/Staff/JH/MIEL/MIELUpdated.pdf
    The first method I described (give the extras to those with the highest decimal parts) is called "Hamilton's Method". George Washington vetoed this proposal in 1790: he didn't like the fact that Maryland (akin to state B) would get a representative that should have gone to Delaware (C).
    Apparently no "paradox free" solution is possible (Balinski and Young's theorem).
    The actual method used since 1942 - "Hill's method" - is described in detail.

  • Array.sort() question

    I've been looking at Arrays and the Comparator interface. But I don't understand the sorting results:
    import java.util.*;
    import java.io.*;
    class SearchObjArray {
         public static void main(String[] args) {
              Console con=System.console();
              if (con==null) System.exit(1);
              String[] sa={"one","two","three","four"};
              Arrays.sort(sa);          
              con.format("The sorted string:%n");          
              for(String s: sa)
                   con.format("%s ",s);
              //four,one,three,two
              con.format("%nA binary search for \"one\": one=%s%n",Arrays.binarySearch(sa,"one"));
              //one=1, as expected. The binarySearch found "one" in position 1 of the sorted array.
              ReSortComparator rs=new ReSortComparator();     
              con.format("A binary search for \"one\" using the resort comparator on the string array: one=%s%n",Arrays.binarySearch(sa,"one",rs));
              //one=-1<====WHY -1? Why is the insertion point 0?
         static class ReSortComparator implements Comparator<String> {
              public int compare(String a, String b) {
                   return b.compareTo(a);
              

    You have to search using the same ordering rules as how the array is sorted. You sorted with one set of rules (String's natural ordering) and searched with a different set of rules (the opposite ordering, as determined by your comparator). That's the same as trying to do a binary search on an unsorted array. Since one of the preconditions of binary search is that the array be sorted, it shouldn't be surprising that you get odd results.

  • Address book field sort question

    Does anyone know how I can set upp my City field so I can sort by city? When I call customers for appointments I would like to sort by city so I can group all my calls together. Presently I group it in with Last name which does not work well if I want to do a mailing.
    Note to Palm; Why wouldn't Palm have set City field seperately so you can sort by city?
    Post relates to: Tungsten E2

    McAfee will warn you about anything sometimes lol. I've downloaded about 10 different programs and no viruses yet, so you shouldn't need worry. There should be some sort of advanced search tool on that site. You can also try using google. I do apologize the device does not come with that search method natively. I hope you find what you are looking for though through add ons.
    Let me know if you have any further questions and have a nice day.
    Post relates to: Treo 800w (Sprint)

  • Sort Question

    I created a report that has many columns that are sortable. Everytime I select a column to sort by it does it by ASC. Selecting it a second time gives DESC order. Is there a way to setup the reports so that the first time a column is sorted it gives the results in DESC order first.

    Okay, well, you want to sort a list on an integer right? The integer represents the number of occurrences of each element. You need a way to associate the number of occurrences with the element whose count it represents. Sounds to me like a class with one int member variable being the count and another being the element you're counting.
    You'd then want to either make that class Comparable, or define a Comparator, and have the respective compareTo() or compare() method look at the count field.
    You'd need to iterate over your original list, keeping track of how many times each element occurs, and then construct objects of your element/count class appropriately.

  • Collator sorting question

    Good Day!
    I have a program, witch uses Collator class object to print numbers in order.
    Collator collator = Collator.getInstance(Locale.US);
         Collections.sort(num, collator);
    for ( i = 0; i < num.size(); i++) {
    String num1 = num.get(i);
    System.out.println("num = " + num1);
    As a result I receive
    num = 1
    num = 1
    num = 10
    num = 10
    num = 100
    num = 100
    num = 101
    num = 101
    num = 102
    num = 102
    num = 2
    num = 2
    num = 20
    But it's necessary to make numbering order as 1 1 2 2 3 3 ...
    I wonder if there is any solution to make Collator class object to understand shorter String sentences as bigger than longer ones. (For an example to understand that 2 is bigger than 10, or 3 is bigger than 20...)
    Thank you for your time!
    Have a nice day!

    What you're describing is most commonly known as the natural sort order (it's also called the intuitive or alphanumeric order). [Here's|http://www.codinghorror.com/blog/archives/001018.html] a good blog post about it. There's no class in the standard libraries that does this, nor is there anything in any public library that I know of. You can find some informal Java implementations (among other languages) by following that link, but here's one I wrote. (Note that it's a Comparator, not a Collator; if you really a Collator, I have one of those too, but it's more experimental.) import java.util.Arrays;
    import java.util.Comparator;
    * <p>A comparator that emulates the "intuitive" sorting used by Windows
    * Explorer.  The rules are as follows:</p>
    * <ul><li>Any sequence of one or more digits is treated as an atomic unit, a
    * number.  When these number units are matched up, they're compared according
    * to their respective numeric values.  If they're numerically equal, but one
    * has more leading zeroes than the other, the longer sequence is considered
    * smaller.</li>
    * <li>Numbers always sort before any other kind of character.</li>
    * <li>Spaces and all punctuation characters always sort before letters.</li>
    * <li>Letters are sorted case-insensitively.</li></ul>
    * <p>Explorer's sort order for punctuation characters is not quite the same
    * as their ASCII order.  Also, some characters aren't allowed in file names,
    * so I don't know how they would be sorted.  This class just sorts them all
    * according to their ASCII values.</p>
    * <p>This comparator is only guaranteed to work with 7-bit ASCII strings.</p>
    * @author Alan Moore
    public class IntuitiveStringComparator<T extends CharSequence>
        implements Comparator<T>
      private T str1, str2;
      private int pos1, pos2, len1, len2;
      public int compare(T s1, T s2)
        str1 = s1;
        str2 = s2;
        len1 = str1.length();
        len2 = str2.length();
        pos1 = pos2 = 0;
        if (len1 == 0)
          return len2 == 0 ? 0 : -1;
        else if (len2 == 0)
          return 1;
        while (pos1 < len1 && pos2 < len2)
          char ch1 = str1.charAt(pos1);
          char ch2 = str2.charAt(pos2);
          int result = 0;
          if (Character.isDigit(ch1))
            result = Character.isDigit(ch2) ? compareNumbers() : -1;
          else if (Character.isLetter(ch1))
            result = Character.isLetter(ch2) ? compareOther(true) : 1;
          else
            result = Character.isDigit(ch2) ? 1
                   : Character.isLetter(ch2) ? -1
                   : compareOther(false);
          if (result != 0)
            return result;
        return len1 - len2;
      private int compareNumbers()
        int delta = 0;
        int zeroes1 = 0, zeroes2 = 0;
        char ch1 = (char)0, ch2 = (char)0;
        // Skip leading zeroes, but keep a count of them.
        while (pos1 < len1 && (ch1 = str1.charAt(pos1++)) == '0')
          zeroes1++;
        while (pos2 < len2 && (ch2 = str2.charAt(pos2++)) == '0')
          zeroes2++;
        // If one sequence contains more significant digits than the
        // other, it's a larger number.  In case they turn out to have
        // equal lengths, we compare digits at each position; the first
        // unequal pair determines which is the bigger number.
        while (true)
          boolean noMoreDigits1 = (ch1 == 0) || !Character.isDigit(ch1);
          boolean noMoreDigits2 = (ch2 == 0) || !Character.isDigit(ch2);
          if (noMoreDigits1 && noMoreDigits2)
            return delta != 0 ? delta : zeroes2 - zeroes1;
          else if (noMoreDigits1)
            return -1;
          else if (noMoreDigits2)
            return 1;
          else if (delta == 0 && ch1 != ch2)
            delta = ch1 - ch2;
          ch1 = pos1 < len1 ? str1.charAt(pos1++) : (char)0;
          ch2 = pos2 < len2 ? str2.charAt(pos2++) : (char)0;
      private int compareOther(boolean isLetters)
        char ch1 = str1.charAt(pos1++);
        char ch2 = str2.charAt(pos2++);
        if (ch1 == ch2)
          return 0;
        if (isLetters)
          ch1 = Character.toUpperCase(ch1);
          ch2 = Character.toUpperCase(ch2);
          if (ch1 != ch2)
            ch1 = Character.toLowerCase(ch1);
            ch2 = Character.toLowerCase(ch2);
        return ch1 - ch2;
      public static void main(String[] args)
        String[] list =
          "foo 03",
          "foo 00003",
          "foo 5",
          "foo 003",
          "foo~03",
          "foo 10far",
          "foo 10boo",
          "foo 10",
          "foo!03"
        Arrays.sort(list, new IntuitiveStringComparator<String>());
        for (String s : list)
          System.out.println(s);
    }

  • Last sorting question Itunes!?

    Hi there,
    I haven't really found the answer i was looking for in this support community. Hopefully someone has the right answer for me. Sorry for the image being Dutch, but i will explain in English.
    The thing i want to do is:
    1. Being able to see a various artists album in one group (1 coverflow). This i know how to do, on the left side of the image you'll see.
    Naam = name or title if you like
    Artiest = artist
    Album-artiest = album artist (by keeping this in format of Various Artists, this keeps the album ''together'' as one cover)
    Album = Album
    On the right side
    Naamsortering = name sorting (obvious blank, since there are multiple titles in this album, otherwise it sorts no more on the artist which i prefer instead of                          title order)
    Artiestsortering = Artistsort (here i copied the artistname, so in the artist list it sort there on alfabetical order) Doesn't work btw see part 2 of my question.
    Albumartiest-sortering = (here again i copied the artistname, so when you view a album it sorts the tracks on artist order, i like that!)
    Albumsortering = albumsort (this is for sorting the album between other albums on alfabetical order)
    So i think i got this end covered. Now for part two.
    2. Search on my Apple TV within artist for example: ''Ultravox'' (see picture above).
    The problem i'm having here is that this artist ''Ultravox'' couldn't be found by the search query of my Apple TV. Why is that? I stated that the Artist is named ''Ultravox'', but never the less it can't be found unless i change the album-artist field into ''Ultravox''. But this looses the keeping the album ''together'' as one cover.
    So could anyone tell me if its possible to maintain the various artist album and still be able to search for an artist in this album on a Apple tv?
    Already many thanks in advance for your time and help

    Ah, that's the same fix as I describe in One album, still too many covers. I've no idea why iTunes does this one either. Funnily enough it seems to happen sometimes when I rename an existing album which is properly grouped so I know the values must be consistent because I've only just changed them, and did so all at the same time.
    tt2

  • Guide Sorting Question

    I just switched to FIOS and couldn't find an answer to this question.
    I noticed that I can select all of the Action movies or Comedies, etc on a particular day, but it doesn't show the time they are showing. I'd like to be able to sort by a theme at the current time and later. Is this possible?
    Thanks

    Hi,
    There is no real good way to do what you want to do.  You can go to menu> search> interest and that will give you shows coming on in the future.  A great way to search is by using your PC and going to www.verizon.com/fiostvcentral and you can do all sorts of searches in there.
    Thanks,
    Frank_VZ
    Frank
    CET/Social Media
    Notice: Content posted by Verizon employees is meant to be informational and does not supersede or change the Verizon Forums User Guidelines or Terms or Service, or your Customer Agreement Terms and Conditions or Plan.

  • Sorting questions; albums together within genres?

    Hi!
    I have some questions concerning the way iTunes sorts my Library.
    I'd like it to sort the classical section on composer, instead of artist. My library is sorted on Genre primary, and perhaps it's impossible to sort only one genre on Genre-Composer-Album . If so, I'll accept that.
    However, this next one should be possible in some way:
    How do I get iTunes to keep tha different albums sorted together in Soundtrack genre? For instance, the Buffy Ultimate Album keeps getting mixed up with Lock Stock and Two smoking barrells album, despite that I've checked "part of a collection" and entered specific CD track numbers for every one of the tracks. I even tried entering "Buffy ultimate soundtrack" into the Grouping field. What does that one do if not keep them together?
    Help please...

    How do I get iTunes to keep tha different albums sorted together in Soundtrack genre?
    I would really like to know the same thing!!!! I have a lot of movies and B'Way soundtracks that I would like to peruse by album title. It seems the ipod only lets me browse by song and I agree, they all get jumbled together.
    I am now in the process of dragging them all into a soundtracks playlist, which is a little better because at least the songs stay in the right order. I would love to be able to drag the album title into the playlist and then go onto the next song list screen from there.
    I am going to suggest it on the feedback page.
    I hope someone can shed some light on what can be done about this.

Maybe you are looking for

  • XML - Oracle Approach

    Hi, I've a client that is in the begining of a Intranet using Oracle Portal. They are very excited about this new tool, and ask for more options to develop some custom applications, this new applications should work in Oracle Portal and be reusable w

  • Why is my publishing page blank?

    I have a Macbook Pro (Leopard) and have just created a website and cannot publish it, cause the publishing page is white - empty - blank? Why is that?

  • Run-time error '5240'

    Hello, We have a problem with a user when he tries to open a favorite workbook in Bex Analyzer. We work with BW 3.1. I execute: Open + Workbook + Favorites and the next message is displayed: Run-time error '5240' Can not use a node of type leaf *** p

  • Can someone help me transfer files from old apple to new

    hi i recently got a new (used) laptop. To bring files from my old g4 to my new laptop can i create a network between the two with just cord? ibook   Mac OS X (10.4.7)  

  • IPhoto default

    I have update my iPhoto with iPhoto'11 version 9.1.2 .I have purchased it on line. All my photos are mixed,there are two libraries!!I can't open many photos on which its writen"iPhoto default" When i click on one of them its appear a exclamation poin