How to sort a set of integers

I have an int array containing a set of integers, and an empty ArrayList.
I want to find the biggest integer and add it into the ArrayList, and then find the second biggest one and add it into the ArrayList as well, and the 3rd biggest one, as so on.
How to achieve that? Could anyone write a sample code for me? Thanks in advance!

Do you really need to follow those steps? Or do you just want to end up with a sorted ArrayList?
If the latter, you can either sort the array with Arrays.sort and then use Arrays.asList to get a List out of it, or you can use Arrays.asList first, and then call Collections.sort on the resulting list.

Similar Messages

  • Sorting a Set with a custom Comparator

    Hi,
    I wondered how to sort a Set with a custom Comparator. I know how to do this with a List: Collections.sort(list,new CustomComparator()).
    But how can I do this with a Set?
    Thanks
    Jonny

    If you want to just sort the Set on demand, you'd have to dump its contents into a List, sort the List, then dump its contents back into a LinkedHashSet.
    If you want the set to always be in sorted order, use a SortedSet, such as TreeSet.

  • How to use addAll with a set of integers in array

    Hi does anyone know how to use void addAll (Set other) with a set of integers?...i want to add all of the integers from the other set to this one. For example, if i have this set {4, 9, 2} and I wanted to add to it all of the integers from another set {3, 2, 8, 4}, the set becomes {4, 9, 2, 3, 8}. I'm stumped on how to do this..if anybody could help, thanks!

    Set1 = ...
    Set2 = ...
    Set1.addAll(Set2);
    addAll(Collection<? extends E> c)
    Adds all of the elements in the specified collection to this set if they're not already present (optional operation). If the specified collection is also a set, the addAll operation effectively modifies this set so that its value is the union of the two sets. The behavior of this operation is unspecified if the specified collection is modified while the operation is in progress.

  • How to Sort Dimension in Pivot Table via Order Column which is changing like Factual values

    Hi,
    Recently in of our product offerings we got stuck on this following question:
    How to Sort Dimension based on the Order Value which Keeps Changing with Factual Values??
    We have a data source laid out as (example)
    In the above the “Order” columns are changing per
    Company/(DimensionA) for DimesnsionB.
    Instead what we want is: (But only if we can get the following result without putting the “Order” Column in the “Values” Section. 
    If there are any configurations that we can make to our power pivot model for the similar data set so that the
    DimesnionB in this case can be sorted by the Order column, would be greatly helpful to us. 
    Sample File:
    http://tms.managility.com.au/query_example.xlsx
    Thanks
    Amol 

    Hi Amol,
    According to your description, you need to sort dimension members in Pivot Table via order column, and you don't want the order column show on the Pivot table, right?
    Based on my research, we can sort the data on the Pivot table based on one of the columns in that table, and we cannot sort the data based on the columns that not existed on the Pivot table. So in your scenario, to achieve your requirement, you can
    add the column to pivot table and hide it.
    https://support.office.com/en-gb/article/Sort-data-in-a-PivotTable-or-a-PivotChart-report-49efc50a-c8d9-4d34-a254-632794ff1e6e
    Regards,
    Charlie Liao
    TechNet Community Support

  • HT4236 Hello, does anyone have any advice on how to sort photos in an albumn on an Iphone by date of photo? I've ordered them all in my Pictures but then when I sync them across through Itunes, they all end up in a jumble on my phone. Thanks!

    Hello, does anyone have any advice on how to sort photos in an albumn on an Iphone by date of photo? I've ordered them all in my Pictures but then when I sync them across through Itunes, they all end up in a jumble on my phone. Thanks!

    When viewing an album on the iPhone you can tap "Photos" at the bottom and that will show all photos by date. Unfortunately though it is all photos, not just the album you are currently viewing.
    What I have done is the following. On the computer I have a main folder (e.g. iPhone photos) and then make sub-folders within that. Placing photos that will be synched to the iPhone into various subfolders gives quite a bit of organizational capablility. In iTunes when you select the main folder to sync, the sub-folders will show on the iPhone as separate albums. Beyond that, in one case where I really wanted a specific sort within an album I renamed the photos on the computer (something like A-picxxx, B-picxxx) so they sorted on the computer alphabetically in the order I want on the phone. That sort order was maintained after the sync.
    Note that each time you sync using iTunes, the non-Camera Roll pictures on the phone will be set to match the current iTunes settings/photos -- so you can experiment.

  • How to transfer a set of data from Excel spread sheet to an Access database

    hi,
    Can any one please tell me how to transfer a set of data from Excel spread sheet to an Access database using SQL query.I'm using java API currently. I have done all sorts of ODBC connection in administrative tools.The file is in correct location. I have done certain coding but with errors.Help me to get rid of these errors,
    Coding:*
    try
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    Connection datacon=DriverManager.getConnection("jdbc:odbc:exdata","",""); *//For Excel driver*
    Connection datacon1=DriverManager.getConnection("jdbc:odbc:stock1","",""); *// For mdb driver*
    Statement datast=datacon.createStatement();
    Statement datast1=datacon1.createStatement();
    ResultSet excelrs=datast.executeQuery("select item_code,sdata,closing_stock from phy "); *//phy is the excel file*
    while(excelrs.next())
    String ic=excelrs.getString("item_code");
    System.out.println(ic);
    String d=excelrs.getString("sdate");
    double cs=excelrs.getDouble("closing_stock");
    int dbrs=datast1.executeUpdate("insert into second values('"+ic+"','"+d+"',"+cs+")"); *//second is the mdb*
    excelrs.close();
    }catch(Exception e)
    System.out.println(e);
    Error:*
    java.sql.SQLException: [Microsoft][ODBC Excel Driver] The Microsoft Jet database engine could not find the object 'C:\JavaGreen\phy.xls'. Make sure the object exists and that you spell its name and the path name correctly.
    thanks,
    kumar.

    JAVA_GREEN wrote:
    No i haven't mixed up.But the file from where i have to retrieve the data is in csv format.Even though i created another csv driver.and tried but i cud not find a solution to load/transfer a set of records from one file(in Excel/csv format) to another file(in mdb format).plz help me.Is there any other methods for this data transfer.A csv file is NOT an excel file.
    The fact that Excel can import a csv file doesn't make it an excel file.
    If you have a csv file then you must use a csv driver or just use other code (not jdbc) to access it. There is, normally, a ODBC (nothing to do with java) text driver that can do that.

  • How to sort a list of strings, without methods and stuff just simple code?

    Hi
    How to sort a list of strings, without methods and stuff just simple code?
    Thanks in adavance!!

    Without methods? How are you going to all the sort code? What is the point of code?
    Collections.sort(List) will sort strings or anything that implements the Comparable interface, or you can use the sort method that takes a Comparator implemenation.
    If you want "just code", you could either get the Collections class souce and follow it to the code. But otherwise, there isn't one set of code. There are various sorting algorithms with advantages and disadvantages. Maybe you'd be better off searching for sorting algorithms and if you understand them, it should be simple to write Java implementations of them.

  • Write an algorithm to sort an array of integers

    "Write an algorithm to sort an array of integers"
    I was asked this at an interview and required to do it in 5 mins. I don't think you can use sort them by putting them in a collection, i think you need to write an algorithm from scartch. Any idea what the best way to do this would have been?

    Depends what you mean by "best."
    BubbleSort is probably the only one I could write off the top of my head in five minutes, but as sorting routines go for practical use, it sucks. If you know how to write MergeSort or QuickSort or dman near anything off off the top of your head, that would proabably be better.
    No one sorting algorithm is "best" without any context, however.
    If you don't know any sorting algorithms, use google or your data structures and algorithms textbook.

  • How to sort a list with numbers?

    Hi!
    How do i sort a list like this:
    ["Amningsnapp 6.c", "Anti-Colic Nappflaska 6.b", "Barn/Baby Underjams Girls 5.b", "Hår Gummisnodd 1.c", "Leksaker 7.a", "Pincett 2.a", "Protes Rengöring 3.a", "Sprayflaska Plast 4.b"]
    ...so that I get a list in number order like this instead:
    ["Hår Gummisnodd 1.c","Pincett 2.a","Protes Rengöring 3.a","Sprayflaska Plast 4.b","Barn/Baby Underjams Girls 5.b","Anti-Colic Nappflaska 6.b","Amningsnapp 6.c","Leksaker 7.a"]
    On mouseUp
    currentItem = the mouseLine
      if the doubleClick = TRUE then
        handlingslista.add (field(12).line[currentItem])
        sort handlingslista
        set x = count (handlingslista)
        repeat with i = 1 to x
          put handlingslista[i] into member(17).line[i]
        end repeat
      end if
    end
    --This is what the list handlingslista contains:
    ["Amningsnapp 6.b", "Anti-Colic Nappflaska 6.b", "Barn/Baby Underjams Girls 5.b", "Hår Gummisnodd 1.c", "Leksaker 7.a", "Pincett 2.a", "Protes Rengöring 3.a", "Sprayflaska Plast 4.b"]

    Assuming the number always occurs as the last word, you could temporarily store the items in the form ["6.c", "Hår Gummisnodd 1.c"], therefore resulting them being sorted lexicographically based on the last word, like this:
    handlingslista = ["Amningsnapp 6.c", "Anti-Colic Nappflaska 6.b", "Barn/Baby Underjams Girls 5.b", "Hår Gummisnodd 1.c", "Leksaker 7.a", "Pincett 2.a", "Protes Rengöring 3.a", "Sprayflaska Plast 4.b"]
    repeat with n = handlingslista.count down to 1
      handlingslista[n] = [the last word of handlingslista[n], handlingslista[n]]
    end repeat
    handlingslista.sort()
    repeat with n = handlingslista.count down to 1
      handlingslista[n] = handlingslista[n][2]
    end repeat
    put handlingslista
    -- ["Hår Gummisnodd 1.c", "Pincett 2.a", "Protes Rengöring 3.a", "Sprayflaska Plast 4.b", "Barn/Baby Underjams Girls 5.b", "Anti-Colic Nappflaska 6.b", "Amningsnapp 6.c", "Leksaker 7.a"]
    Alternatively, you could use Javascript, in which Arrays can be sorted based on an arbitrary ordering: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort.

  • How to sort a file

    How to sort a file, simple unrefractored example
    import java.io.*;
    import java.util.*;
    public
    class Sort
       * Sorts a file that contains data per line using a TreeMap
       * @param args There must be at least one argument, and only the first
       * argument will be interpreted
      public
      static
      void main(String[] args)
      throws Exception
        TreeSet set; // used to sort the data
        BufferedReader buffer; // reads from File with name of args[0]
        PrintWriter writer; // writes to File with the name of args[0].sorted
        String line; // buffer for line read
        set = new TreeSet();
        buffer = new BufferedReader(new InputStreamReader(new FileInputStream(args[0])));
        while ((line=buffer.readLine())!=null) set.add(line.trim());
        buffer.close();
        writer = new PrintWriter(new PrintStream(new FileOutputStream(args[0]+".sorted")));
        for (Iterator i = set.iterator(); i.hasNext(); writer.println(i.next()));
        writer.close();

    and here is the clean version as a handy static utility method:
          * Sort lines in a text file in alphabetical order.
          * @param sourceFile File to sort.
          * @param destinationFile File to write sorted content to.
          * @throws IOException If error occured.
         public static void sortFile(File sourceFile, File destinationFile) throws IOException {
            if (sourceFile != null) {
                BufferedReader br = null;
                PrintWriter pw = null;
                TreeSet treeSet = new TreeSet(); //used to sort the data
                try {
                    String line = null;
                    //read source file into treeSet:
                    br = new BufferedReader(new InputStreamReader(new FileInputStream(sourceFile)));
                    while ((line = br.readLine())!=null) {
                        treeSet.add(line.trim());
                    //write content of treeSet to destination file:
                    pw = new PrintWriter(new PrintStream(new FileOutputStream(destinationFile)));
                    Iterator iterator = treeSet.iterator();
                    while (iterator.hasNext()) {
                        pw.println(iterator.next());
                } finally {
                    if (br != null) {
                        br.close();
                    if (pw != null) {
                        pw.close();
            }//else: sourceFile unavailbel
        }//sortFile()

  • How to sort new mails

    Hello friends
    iam in the process of creating a javamail application iam retriving the messages by the number from the user mail box i would like to show the new messages in the user inbox as they arrive any idea how the sorting could be done
    regards
    hari

    Well sultan thanks a lot
    but iam aware of these methods i have different problem i have set netscape messager here and the netscape imap server just puts all the new mails at last i can check if the mails are unread new etc. by there flags but the problem was retrieving the messages by there number from my imap server i.e netscape messaging server
    any way i have solved the problem
    i have developed a engine in java that does this
    lets work together for this forum
    cheers
    hari

  • Help I am a student and have no idea how to sort this program by Product

    First class:
    // CheckPoint: Inventory Program Part 1
    // Display product information
    public class Product1 //declare class
    //declare instance variables
    private int productNumber,
    inStock;
    private String productName; // List of instance variables unique to object
    private double unitPrice;
    //constructor to handle no input and set defaults
    public Product1()
    //constructor to handle input parameters
    public Product1( int number, String name, int stock, double perPrice )
    productNumber = number;
    productName = name;
    inStock = stock;
    unitPrice = perPrice;
    public void setProductNumber( int number ) //stores product number
    productNumber = number;
    public void setProductName( String name ) //stores product name
    productName = name;
    public void setInStock( int stock ) //stores amount of product in stock
    inStock = stock;
    public void setUnitPrice( double perPrice ) //stores the unit price of product
    unitPrice = perPrice;
    public int getProductNumber() //allows a call to retrieve product number
    return productNumber;
    public String getProductName() //allows a call to retrieve the product name
    return productName;
    public int getInStock() //allows a call to retrieve stock info
    return inStock;
    public double getUnitPrice() //allows a call to retrieve unit price
    return unitPrice;
    public double getInventoryValue()
    return ( (double)inStock * unitPrice );
    public String toString()
    return productName + " - " + unitPrice;
    Second Class:
    import java.text.DecimalFormat;
    public class Inventory1
    private final int maxInventory = 30;
    private Product1 items[] = new Product1[ maxInventory ];
    DecimalFormat formatter = new DecimalFormat( "$##,###.00" );
    public void addProduct( Product1 item )
    for ( int i = 0; i < maxInventory; i++ )
    if (items[i] == null)
    items[i] = item;
    return;
    public double getTotalInventoryValue()
    double sum = 0.0;
    for ( Product1 item : items )
    if ( item != null )
    sum += item.getInventoryValue();
    return sum;
    public void displayInventory()
    boolean hasItems = false;
    for ( Product1 item : items )
    if ( item != null)
    hasItems = true;
    System.out.printf( "%8d%12s%11d%13.2f%14.2f", item.getProductNumber() , item.getProductName(), item.getInStock(), item.getUnitPrice(), item.getInventoryValue() );
    System.out.println( "" ); // display space
    System.out.println("");
    Part 3:
    import java.text.DecimalFormat;
    public class InventoryTest1
    static DecimalFormat formatter = new DecimalFormat( "$##,###.00" );
    public static void main( String args[] )
    Product1 item1 = new Product1( 001, "Staples", 5, 2.99 );
    Product1 item2 = new Product1( 002, "Books", 10, 15.00 );
    Product1 item3 = new Product1( 003, "Printers", 20, 55.00 );
    Inventory1 myInventory1 = new Inventory1();
    System.out.println("");
    System.out.printf( "%s%12s%11s%13s%14s", "Product#", "Name", "In Stock", "Unit Price", "Stock Value" );
    System.out.println("");
    System.out.println("");
    myInventory1.displayInventory();
    myInventory1.addProduct( item1 );
    myInventory1.addProduct( item2 );
    myInventory1.addProduct( item3 );
    myInventory1.displayInventory();
    System.out.println( "" ); // display space
    System.out.println("");
    System.out.println( "Total value of inventory is: " );
    System.out.println ( formatter.format(myInventory1.getTotalInventoryValue() ) );
    I have no idea where to put the sort statement and how to implement it.

    Sorry about that. Before i proceed with the code I will say that I need help trying to determine where to put a sort statement and what sort statement should I use. I have three classes and have no idea how to sort the items by Product name. For instance, I have staples, books, and printers in my code. How do I get it to display these names and all of the corresponding information in alphabetical order. So with that said, here is the code.
    First program:
    // CheckPoint: Inventory Program Part 1
    // Display product information
    public class Product1 //declare class
    //declare instance variables
    private int productNumber,
    inStock;
    private String productName; // List of instance variables unique to object
    private double unitPrice;
    //constructor to handle no input and set defaults
    public Product1()
    //constructor to handle input parameters
    public Product1( int number, String name, int stock, double perPrice )
    productNumber = number;
    productName = name;
    inStock = stock;
    unitPrice = perPrice;
    public void setProductNumber( int number ) //stores product number
    productNumber = number;
    public void setProductName( String name ) //stores product name
    productName = name;
    public void setInStock( int stock ) //stores amount of product in stock
    inStock = stock;
    public void setUnitPrice( double perPrice ) //stores the unit price of product
    unitPrice = perPrice;
    public int getProductNumber() //allows a call to retrieve product number
    return productNumber;
    public String getProductName() //allows a call to retrieve the product name
    return productName;
    public int getInStock() //allows a call to retrieve stock info
    return inStock;
    public double getUnitPrice() //allows a call to retrieve unit price
    return unitPrice;
    public double getInventoryValue()
    return ( (double)inStock * unitPrice );
    }

  • Verity - How to sort results?

    How can one sort a set of data returned by CFSEARCH?
    I'm using CF7.
    Thank you!

    quote:
    Originally posted by:
    therearentanyleft
    I appreciate your comment and will certainly answer questions
    when I know a solution. Thanks for your response. Can you help me
    understand what you mean by "Try query of queries"?
    Only to a limited degree because I've never used
    <cfsearch>
    Macromedia book Developing Cold Fusion MX Applications has an
    example on page 460. The name attribute of your cfsearch tag
    becomes the table name in your cfquery tag. The example alludes to
    a field called score, but I don't know where that came from.

  • HT204053 The entire family has used one itunes account for years. How do we all set up separate iCloud accounts now?

    The entire family has used one itunes account for years. How do we all set up separate iCloud accounts now? Or should we? 5 macbooks, 2 ipads, 4 iphones, 2 itouch, 2 imacs.   How does one decide what to sync, share and what not to? Green Jeans.

    You need to start by understanding the distinction between iTunes and iCloud - Apple confuse the issue by referring to 'iTunes Match' as part of iCloud. It isn't.
    You don't have to have the same login (Apple ID) for iTunes and iCloud; many people don't and there's no problem about it.
    Your iCloud ID gets you email, calendars, contacts, iWork documents and PhotoStream syncing between devices.
    Your iTunes ID gets you the iTunes Store, the App Store for iOS, the Mac App Store for OSX,, 'iTunes in the Cloud' (downloading of purchased items to any logged-in device) and 'iTunes Match' (uploading of songs not purchased in the iTunes Store).
    Your family members can easily each get their own iCloud account to keep email etc. separate - in each case they will need a different non-Apple email address (a free one from Yahoo etc. would do) to set up the ID. If they are sharing a Mac they need to be using a separate user account.
    They can have their own iCloud accounts and still all sign into the same iTunes account: or they can open their own iTunes accounts using their new iCloud Apple IDs.
    BUT they cannot transfer items purchased under the present iTunes ID to different iTunes IDs.

  • How to sort files and folders like Windows

    I don't know if this is specific to Arch or every other Linux distro but one thing that really bugs me in Arch is how files and folders are sorted. I use Windows as my main OS (don't start on that please) and I have one folder properly organized exactly as I want it and I like it how Windows sorts this. I access that same folder from my Arch installation, the problem is that the sorting is different and it gets on my nerves lol...
    This is how Windows sorts that specific folder:
    C:\Users\Nazgulled\Documents\University>dir /O
    Volume in drive C is Vista
    Volume Serial Number is F84E-02BE
    Directory of C:\Users\Nazgulled\Documents\University
    05-08-2009 15:34 <DIR> .
    05-08-2009 15:34 <DIR> ..
    05-08-2009 11:10 <DIR> [Archives]
    05-08-2009 14:38 <DIR> [Developers]
    05-08-2009 11:17 <DIR> [X] 1) Cálculo II
    05-08-2009 11:18 <DIR> [X] 2) Análise de Custos
    05-08-2009 11:18 <DIR> [X] 2) Cálculo de Programas
    05-08-2009 11:18 <DIR> [X] 2) Laboratórios de Informática III
    05-08-2009 11:18 <DIR> 2) Algoritmos e Complexidade
    05-08-2009 11:18 <DIR> 2) Arquitectura de Computadores
    05-08-2009 11:18 <DIR> 2) Comunicaçao de Dados
    05-08-2009 11:18 <DIR> 2) Engenharia Económica
    05-08-2009 11:18 <DIR> 2) Estatística Aplicada
    0 File(s) 0 bytes
    13 Dir(s) 24.700.485.632 bytes free
    And this is how Arch does it:
    nazgulled ~/University $ ls -l
    total 7
    drwxr-xr-x 1 nazgulled nazgulled 4096 2009-08-05 11:18 2) Algoritmos e Complexidade
    drwxr-xr-x 1 nazgulled nazgulled 4096 2009-08-05 11:18 2) Arquitectura de Computadores
    drwxr-xr-x 1 nazgulled nazgulled 4096 2009-08-05 11:18 2) Comunicação de Dados
    drwxr-xr-x 1 nazgulled nazgulled 4096 2009-08-05 11:18 2) Engenharia Económica
    drwxr-xr-x 1 nazgulled nazgulled 8192 2009-08-05 11:18 2) Estatística Aplicada
    drwxr-xr-x 1 nazgulled nazgulled 4096 2009-08-05 11:10 [Archives]
    drwxr-xr-x 1 nazgulled nazgulled 4096 2009-08-05 14:38 [Developers]
    drwxr-xr-x 1 nazgulled nazgulled 4096 2009-08-05 11:17 [X] 1) Cálculo II
    drwxr-xr-x 1 nazgulled nazgulled 12288 2009-08-05 11:18 [X] 2) Análise de Custos
    drwxr-xr-x 1 nazgulled nazgulled 4096 2009-08-05 11:18 [X] 2) Cálculo de Programas
    drwxr-xr-x 1 nazgulled nazgulled 4096 2009-08-05 11:18 [X] 2) Laboratórios de Informática III
    How can I get Arch/Linux to sort exactly the same as Windows?
    Last edited by Nazgulled (2009-08-05 14:41:47)

    toad wrote:
    Nazgulled wrote:Surely there must be a way to have the same sorting collation in Linux like in Windows
    Ah, no. The way they are doing it is nonsensical and not good practice for a unix style system. Having said that, some solutions have already been offered in this thread.
    While you are free to continue to ask others to help you achieve your aims, it may be more convenient for you to adapt to a structure that is displayed the same way under all systems (just to avoid frustration - not saying you _should_ do it ).
    I really don't care if it's nonsensical, I use Windows 95% of the time or more, it's my main OS, I'm used to it and I like it. Why should I care if it's not a good practice for a unix style system? I just want things to behave the way I like and for a free system like Linux where it doesn't even compare to Windows in terms of freedom in what I can do with it and configure the way I like, it sure is hard to change the way folders/files are sorted...
    It sucks that there isn't a proper solution but I'm not going to adapt anything, that would be nonsensical... But if I have to, I can live with the fact that there isn't a good solution and leave it as it is
    Thanks everyone for their input, "topic closed".

Maybe you are looking for