Sort a Set by entries of an Array

Hi,
I'm stuck here. I want to sort a Set by entries of an Array.
For example:
// Set of persons (Person has a country getter-method)
Set persons = getPersons();
// Array of Strings
String[] countrys = getCountrys();
// here I want to sort the set of persons by country name
???What is the right way to go?
Thanks
Jonny

It sounds like you'll want to write a custom Comparator...
The Java� Tutorial - Object Ordering
Making Java Objects Comparable

Similar Messages

  • In XML view, how to set sap.ui.core.CSSSize array for property "widths" of MatrixLayout Control?

    As SAPUI5 prefer XML views, I'm rewriting JS view into XML views.
    When I translate the statements below, I can not set sap.ui.core.CSSSize array for property "widths" of Control MatrixLayout.
    JS version:
    var oLayout = new sap.ui.commons.layout.MatrixLayout({
        id : 'matrix3'
        columns : 3,
        width : '600px',
        widths : ['100px', '200px', '300px']
    XML version:
    <l:MatrixLayout
        id="matrix3"
        columns="3"
        width="600px"
        widths="['100px', '200px', '300px']">
    <l:MatrixLayout>
    The error says: Uncaught Error: "[100px, 200px, 300px]" is of type object, expected sap.ui.core.CSSSize[] for property "widths" of Element sap.ui.commons.layout.MatrixLayout.
    Same problem with property `backgroundDesign` of MatrixLayoutCell, I can only use a workaround to use String "Fill1" not the Class "sap.ui.commons.layout.BackgroundDesign.Fill1".
    When we meet a property which need a Class object as value, we can not set it in String Format for XML views. That's a pity or I did not find the right way to set NON-String values as property for XML Controls.

    Hi,
    any settings that are not possible in the XML, need to be set in the controller instead.
    Using the string value of an enum is fine, though.
    Regards
    Andreas

  • When I updated by iphone with IOS7, my calendar entries did not follow the icloud.  I am only showing pre set calendar entries for the year?

    When I updated by iphone with IOS7, my calendar entries did not follow the icloud.  I am only showing pre set calendar entries for the year and lost all other calendar entrie and it will not take any new entries.  They show up in my outlook, but not on my iphone, which they did before I updated my software to the new i0s7

    Before syncing, select each calendar on your Mac and back it up by going to File>Export>Export.  If anything goes missing, you can use these to restore your calendars.
    Have you tried simply force closing the calendar app on your iPhone?  To do this, double-tap the home button, locate the calendar app, then swipe up on the image above the app icloud to close it and tap the home bottom.  Then test your calendar again.

  • Public Set Map.Entry Object, Object entrySet() {} // Wut means this line?

    public class ClasseTeste extends AbstractMap
    /** Creates a new instance of ClasseTeste */
    public ClasseTeste() {
    public Set<Map.Entry<Object, Object>> entrySet() {
    Thanks!

    public class ClasseTeste extends AbstractMap
    /** Creates a new instance of ClasseTeste */
    public ClasseTeste() {
    public Set<Map.Entry<Object, Object>> entrySet() {
    Thanks!Its a new feature of java 1.5 called generics.
    here
    Set<Map.Entry<Object, Object>> means this set will contain objects of type Map.Entry only.
    Wid generics u can avoid casting n define generic types.
    sudhir
    http://www.jyog.com

  • 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 delete a random set of indizes from an array as fast as possible?

    Hello,
    My question sounds a bit like this thread but it isn't...    :-(
    http://forums.ni.com/ni/board/message?board.id=170​&message.id=129888&query.id=10689#M129888
    When sampling position/force/resistance data I use a time triggered sampling approach. For later analysis I need (among others) force (Y) over position (x).
    To get this I calculate the mean force from all time points with equal positions (as time is my common index). That works quite well but with arrays over 300000 points it becomes a bit too slow...
    These are my steps so far:
    1. Sort the position array
    2. Eliminate duplicates from the position array (no array reshape in loop)
    3. With the data from 2. get all indices where my original position array has a given value
    4. With the indices from 3. get the corresponding force values from the force raw data and calculate the mean
    In step 3 I need to search the whole raw position array as many times as there are different position values in itself.
    If I could delete all indizes I already found from the array to search that should (in theory) significantly improve performance. On the other hand such an operation would mean a lot of array reshape operations.
    What is the best approach to delete the found indizes?
    OR
    Is there no benefit in deleting the indizes as the array operations to do this need more time than they save?
    Thanks!
    Sören

    Now I'm getting a bit more confused about the app.  If you need a sampling rate higher than the encoder can provide, then then only way I can think of to accumulate multiple readings at the same position is if you have some type of bi-directional cyclical motion.  But if you originally used the encoder as a sampling clock, that seems to imply a unidirectional motion.  Is the motion cyclical or unidirectional?
    Knowing that I need to do some similar processing down the road, I did a bit of tinkering today.  The method I described earlier took ~350 msec to process (sort and then calculate averages force per unique position) on 350,000 data points.  A little more tinkering gave me a method that took <100 msec.  The machine was a pretty new test PC with a 2.8 GHz Pentium.  Here's an outline and perhaps I'll be able to scrub the code a bit to post soon.  Hopefully someone will have some even better ideas!
    The basic idea is essentially a histogram where each possible integer position value maps to a histogram bin.
    1. Based on knowledge of your test equipment, you can know the # of unique positions that can possibly be recorded.  Pre-initialize 2 arrays of this size before starting the main data acquisition.  Both should be full of floating-point 0's.  These will hold (a) count of entries and (b) sum of forces.  Call them the binning arrays.  My test used a size of 8000 possible positions.
    2. An auto-indexing For loop goes through the 350,000 integer positions and floating point forces.  The binning arrays enter this loop through shift registers.
    3. For each pair, use the integer position to map yourself to the appropriate index of the binning arrays.  Increment that element of the count array and add this iteration's force value to the sum array.
    4. After loop completes, divide sum array by count array.  These are your average forces.  (This is why the count is computed as a floating point value.  It was very costly to allow a type coercion from an integer count array into the division function.)  Note that unsampled positions should have 0 counts and produce a NaN result from the division.
    There are also ways to calculate a running average in the loop, but I haven't checked (yet) to see if it's faster.  The median you mentioned would need some extra post-loop steps.
    I'm sure that if this were a coding challenge, someone would cut the processing time at least in half...  Anyone out there?
    -Kevin P.

  • 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.

  • How to set the value of an array element (not the complete array) by using a reference?

    My situation is that I have an array of clusters on the front panel. Each element is used for a particular test setup, so if the array size is three, it means we have three identical test setups that can be used. The cluster contains two string controls and a button: 'device ID' string, 'start' button and 'status' string.
    In order to keep the diagrams simple, I would like to use a reference to the array as input into a subvi. This subvi will then modify a particular element in the array (i.e. set the 'status' string).
    The first problem I encounter is that I can not select an array element to write to by using the reference. I have tried setting the 'Selection s
    tart[]' and 'Selection size[]' properties and then querying the 'Array element' to get the proper element.
    If I do this, the VI always seems to write to the element which the user has selected (i.e. the element that contains the cursor) instead of the one I am trying to select. I also have not found any other possible use for the 'Selection' properties, so I wonder if I am doing something wrong.
    Of course I can use the 'value' property to get all elements, and then use the replace array element with an index value, but this defeats the purpose of leaving all other elements untouched.
    I had hoped to use this method specifically to avoid overwriting other array elements (such as happens with the replace array element) because the user might be modifying the second array element while I want to modify the first.
    My current solution is to split the array into two arrays: one control and one indicator (I guess that's really how it should be done ;-) but I'd still like to know ho
    w to change a single element in an array without affecting the others by using a reference in case I can use it elsewhere.

    > My situation is that I have an array of clusters on the front panel.
    > Each element is used for a particular test setup, so if the array size
    > is three, it means we have three identical test setups that can be
    > used. The cluster contains two string controls and a button: 'device
    > ID' string, 'start' button and 'status' string.
    >
    > In order to keep the diagrams simple, I would like to use a reference
    > to the array as input into a subvi. This subvi will then modify a
    > particular element in the array (i.e. set the 'status' string).
    >
    It isn't possible to get a reference to a particular element within an
    array. There is only one reference to the one control that represents
    all elements in the array.
    While it may seem better to use references to update
    an element within
    an array, it shouldn't really be necessary, and it can also lead to
    race conditions. If you write to an element that has the
    possibility of the user changing, whether you write with a local, a
    reference, or any other means, there is a race condition between the
    diagram and the user. LV will help with this to a certain extent,
    especially for controls that take awhile to edit like ones that use
    the keyboard. In these cases, if the user has already started entering
    text, it will not be overwritten by the new value unless the key focus
    is taken away from the control first. It is similar when moving a slider
    or other value changes using the mouse. LV will write to the other values,
    but will not rip the slider out of the user's hand.
    To completely avoid race conditions, you can split the array into user
    fields and indicators that are located underneath them. Or, if some
    controls act as both, you can do like Excel. You don't directly type
    into the cell. You choose w
    hich cell to edit, but you modify another
    location. When the edit is completed, it is incorporated into the
    display so that it is never lost.
    Greg McKaskle

  • Purchase Order - Issue storage location set mandatory entry

    Hello All,
    When create subcontracting PO, want to set the field of Issue storage location as mandatory.
    I tried to find configuration "Materials Management>Purchasing>Purchase Order-->Define Screen Layout at Document Level", but there is not entry "Issue storage location" to set the screen layout field.
    I searched previous threads, but only find some to mention issue storage location for STO. Now, I just use subcontracting PO that is same as NB document type.
    Please your kind suggestion or any method to set  Issue storage location as mandatory in PO.
    Thanks very much!
    Mag

    Hi ,
    Please, could you re-check it again, I have found storage location and issue storage location fields under define fields for fields selection group.
    Under Field selection group NBF Purchase order
    Selection group                    supplying plant
    Issue storage location required entry chose
    Under Field selection group NBF Purchase order
    Selection group                    Basic data item
    Storage location   required entry chose 
    After this setting, I can be find this storage location fields as Mandatory.
    Regards,
    Thiru

  • Data entry type in array of clusters

    Hi i have 4 column array of cluster
    X Y Z & Data entry Type 
    X+Y=Z simply
    I wanna do this 
    when i entry x; data type cell will auto X (not numerical value just "X")
    when i entry z; data type cell will auto Z 
    Then i can build my algorithm.
    How can i do this.
    Thanks.
    Solved!
    Go to Solution.

    As i said, you image displays a STRING table.
    If you want something like Excel with predefined datatypes for columns, an array of cluster can work out.
    But building an algorithm which checks for specific dependencies within a single record/row
    a) is very specific
    b) can get quite complex.
    That being said, you have to start by looking at these dependencies and evaluate if rows can swap/be in arbitrary order.
    Simply stating:
    row 0 => column 0 is of interest
    row 1 => column 1 is of interest
    row 2 => column 2 is of interest
    will most likely not work.
    Norbert
    CEO: What exactly is stopping us from doing this?
    Expert: Geometry
    Marketing Manager: Just ignore it.

  • Setting up a multi dimensional array of objects

    Hey ya'll. How would i setup a multi dimensional array with this structure?
    TypeSave(Title, material(name, quantity))
    TypeSave[1](Lego Shop, material[1](Lego Blocks, 100))
                   material[2](Roof, 1))
    TypeSave[2](Lego Car, material[1](Door, 2))
              material[2](Gravy, 3, ounces))
    TypeSave will be saved as a serialised object to a file so i can load everything within it and keep the structures integrity.
    I'll have an add button that will add the name and quantity to the next empty position of "material" array. This will then be listed in a list box and allow me to save all the materials with a title to the TypeSave list in the next empty position.
    I'm getting mightily confused how to set up the classes and the array structure :(
    Any help would be greatly appreciated!

    private TypeSave t = new TypeSave();
    private void btnSaveItemActionPerformed(java.awt.event.ActionEvent evt) {                                             
            t.addItem(txtItemTitle.getText(), new Material(txtMaterialName.getText(),txtQuantity.getText()));
            t.saveToFile();
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new MainForm().setVisible(true);
        class Material implements Serializable {
         String name = null;
         String quantity = null;
         //To restrict default constructor
         private Material() {
         public Material(String name, String quantity) {
              this.name = name;
              this.quantity = quantity;
         public String getName() {
              return this.name;
         public String getQuantity() {
              return this.quantity;
         public String toString() {
              return "Name : " + this.name + "Quantity : " + this.quantity;
    class TypeSave implements Serializable {
         private Hashtable items = null;
         public TypeSave() {
              items = new Hashtable();
         public void addItem(String title,Material material) {
              ArrayList materials = (ArrayList) items.get(title);
              if(materials == null) {
                   materials = new ArrayList();
                   items.put(title,materials);
              materials.add(material);
         public Hashtable getItems() {
              return this.items;
         public ArrayList getItem(String title) {
              return (ArrayList)this.items.get(title);
            void saveToFile() {
        ObjectOutputStream oos = null;
            try
            oos = new ObjectOutputStream(new FileOutputStream("item.ser"));
            catch (IOException i)
              System.out.println( "Error opening file");
          try
            oos.writeObject(items);
            catch (IOException o)
                System.out.println("Error writing file");
          try
              if(oos != null)
              oos.close();
            catch (IOException x)
                System.out.println("Error closing file");
    }My save class was working, but i tried to merge it to test this code structure and now it's failing with excepion:
    "Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException"
    any ideas?

  • Sort Result set in Custom Order

    Hello - Happy Friday everyone !!
    I would like result set to be sorted in a custom order, for example, a specific value must appear at top of result set, a specific value must appear at bottom of result set, and others can be sorted in standard order.
    Below is the link I found while researching for the possible solution. This works great if I have to sort a specific value to appear at top of result set but I want some specific values to appear at the very bottom as well.
    http://sqlandme.com/2013/11/18/sql-server-custom-sorting-in-order-by-clause/
    For example:
    CountryName
    AUSTRALIA
    BANGLADESH
    CHINA
    FRANCE
    INDIA
    JAPAN
    NEW ZEALAND
    PAKISTAN
    SRI LANKA
    UNITED KINGDOM
    UNITED STATES
    Now based on the popularity you might need a country to appear on top of the list. In order to return results as required, we need to specify a custom sort order in ORDER BY clause. It can be used as below.
    The following query will return result set ordered by CountryName, but INDIA at top and CHINA at 2nd "container">
    USE [SqlAndMe]
    GO
    SELECT CountryName
    FROM   dbo.Country
    ORDER BY CASE WHEN
    CountryName = 'INDIA' THEN '1'
                  WHEN
    CountryName = 'CHINA' THEN '2'
                  ELSE
    CountryName END ASC
    GO
    Result Set:
    CountryName
    INDIA
    CHINA
    AUSTRALIA
    BANGLADESH
    FRANCE
    JAPAN
    NEW ZEALAND
    PAKISTAN
    SRI LANKA
    UNITED KINGDOM
    UNITED STATES
    My predicament: Based on the example above, I always want 'India' and 'China' at the TOP and 'Bangladesh' and 'Pakistan' at the bottom. Rest can follow the general sort rule. How do I tweak/approach this? Thank you very
    much for your help in advance.
    Result Set I am anticipating;
    INDIA
    CHINA
    AUSTRALIA
    FRANCE
    JAPAN
    NEW ZEALAND
    SRI LANKA
    UNITED KINGDOM
    UNITED STATES
    BANGLADESH
    PAKISTAN
    This would make my weekend great!!
    Regards,
    SJ
    http://sqlandme.com/2013/11/18/sql-server-custom-sorting-in-order-by-clause/
    Sanjeev Jha

    this would be enough
    USE [SqlAndMe]
    GO
    SELECT CountryName
    FROM dbo.Country
    ORDER BY CASE CountryName
    WHEN 'INDIA' THEN 1
    WHEN 'CHINA' THEN 2
    WHEN 'BANGLADESH' THEN 4
    WHEN 'PAKISTAN' THEN 5
    ELSE 3
    END,CountryName
    GO
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

  • How can I auto-sort with each new entry

    I'm looking for a formula, a script, or automator service that will allow me to auto-sort by column every time I change an entry.
    My spreadsheet uses steppers. I want to automatically sort the column every time I increase the stepper.
    I'd prefer not to right click on the column to sort.
    any help?

    Not possible within your data table (the ne in which the stepper is changed), but a second table could show the sorted results, and be automatically updated whenever the steper in the first table is changed.
    Here's an example:
    The image above shows the starting position. Column A of "Data" contains the stepper cells.
    Column B, which may be hidden, contains a formula which modifies the stepper value to ensure that each cell contains a value unique within that column by adding a fractional amount dependent on the row in which the conversion is done. The value used in the formula (1000) will work for up to about 490 rows before rounding (used in the first column of the "Sorted" table) will return a result different from the integer value of the stepper. For more rows, replace 1000 with a larger number.
    Data::B2, and filled down: =A2+ROW()/1000
    The second table, "Sorted" sorts the rows of Data using the values in column B as the sort key. Sorted contains one formula, filled into every body cell on the table, and modified in column A:
    Sorted::A2, filled right: =VLOOKUP(SMALL(Data :: $B,ROW()-1),Data :: $B:$E,COLUMN())
    After filling right, modify the formula in A2 by adding ROUND( in front of VLOOKUP and ,0) after COLUMN())
    Sorted A2: =ROUND(VLOOKUP(SMALL(Data :: $B,ROW()-1),Data :: $B:$E,COLUMN()),0)
    Select cells A2:D2, then Fill down.
    In the image below, the stepper in row 10, which held 9 originally, has been stepped down to 4. There is no change in the order of the table "Data", but "Sorted" automatically resorts the rows to match the new stepper value:
    Regards,
    Barry

  • Set of unique controls within array

    Is it possible to get a set of unique, individual controls with different ranges within an array of controls?
    This is not the default operation.
    For example, I'm using Analog Output VI with Fieldpoint AO module.
    I have distinct scaling on each channel and need controls whose ranges fit each individual scale.
    I don't want to create a separate VI for each channel one the AO module.  Surely that's not necessary.

    Hello Wes,
    It sounds to me like you are trying to configure these ranges such that your user cannot select values that are outside of an acceptable range. If this is the case, then a cluster control on the front panel would allow you to individually control these input ranges. Using the cluster to array function, you will then convert the user's selection to a numeric value in an array. As you have seen, you can then write these values to the FieldPoint VIs as an array. Because those values are inherently within the ranges specified, it should not matter that the individual array elements are not configured for range.
    I hope this information is useful for you. Please post back if I have misunderstood your application. Thanks,
    Mike D.
    National Instruments
    Applications Engineer

  • Hierarchy display Sort Order setting "As in hierarchy" in BEx not working.

    Hi Team,
    We are using SAP BW 7.0
    In a Query the property for Sort Oder of Hierarchy is set as "As in the hierarchy" for WBS_ELEMT.
    Example data as per R3:
    HierarchyID   hierarchyDescription
    4       Four
    2       Two
    1       One
    3       Three
    5       Five
    The setting of sort order by"KEY" with "Ascending" is working fine.
    The setting of sort order by"KEY" with "Descending" is working fine.
    The setting of sort order by"Description" with "Ascending" is working fine.
    The setting of sort order by"Description" with "Descending" is working fine.
    BUT the setting of sort order by "As in the hierarchy" is not effected. 
    In other words, i am able to set it and save & run.  But the result does not have the effect.  It holds the previous setting.
    Is there any pre-requisite to have this setting.
    Please help.
    Regards
    BaaRaa.

    HI Baa Raa,
    This should work, have you tested this on the latest patching by upgrading one machine to :
    gui patch 18 for gui 7.10
    frontend patch 12.01 for 7x tools and gui 7.10
    and
    frontend patch 9 for 3x tools and gui 7.10
    best regards
    Orla.

Maybe you are looking for

  • Price difference between PO and the Info Record

    Dear Experts, I am seeing a strange problem in the MM pricing, the issue is when i am trying to create a new PO for a specific material the condition record is being updated with the wrong price, when i checked the Info Record it has two prices old a

  • IPhoto 6 and Makernotes!!!!!

    I'm dying to know. Has iPhoto 6 fixed the ridiculous load times for those with the unfortunate luck of having cameras that create large makernotes!? Please tell me if you know! I can't wait to actually have a photo program that works the way it shoul

  • Several tracks don't give any sound.

    I made a podcast episode, which I have exported into AAC and what not. Today I opened the project to export an mp3 version, and when i was done I noticed only 2 of the 5 tracks were exported. So I go back into Garageband, and all but one track is pla

  • FM to change amount to external format

    Hi, I'm looking for an FM to change an internal amount with format ######.## to an external format: ###.###,## (european). Any help will be appreciated. regards, bert

  • No Library templates in CS5

    I have the Production Premium suite installed But Encore shows no library templates. I put in the installation disk again, but it said that everything for Encore is installed. How do I get to see the templates? Thanks, Linda