Questions on filtering and sorting an arraylist

Hello All,
I'm trying to figure out a better way to do this code, but what I'm doing is taking an arrayList and filtering it using iter.remove(), based on a criteria I have, then take the results and sort them. The code below works, but I was seeing class cast exceptions when I tried to do a ss.addAll(list);
, but it worked when I just added the set object. Why is this and is there a better way to do all this?
Set set = new HashSet();
List retList = new ArrayList();
SortedSet ss = new TreeSet();
for(Iterator iter = list.iterator(); iter.hasNext();){
.//More code...
iter.remove();
//Remove duplicates.
set.addAll(list);
ss.add(set);
retList.addAll(set);
return retList;

Your current code is adding the set (the hash set) as one element (the only element?) of the sorted set. Is this what you want to do? Would you rather add each element of the set to the sorted set?
I don't know about the class cast exceptions. If you want somebody's comment on this part, you may consider posting code and stack trace.
I think I'd rely on Collections.sort() for sorting rather than TreeSet. If you prefer TreeSet, why not skip the hash set in between?
Hope this helps.
Please remember the code button/tags.

Similar Messages

  • Web dynpro abap applications in filtering and sorting in tables

    Anyone can send me some simple applications based on
    webdynpro abap filtering and sorting concepts in tables....

    >
    cranjith kumar wrote:
    > Anyone can send me some simple applications based on
    > webdynpro abap filtering and sorting concepts in tables....
    First of why not use the ALV Component.  It has built in filtering and sorting so that you don't have to program those aspects.  It also has a nice UI for letting the user design the sorting and filtering that they want. 
    If you need sorting and filtering in the table UI element instead, you don't need anyone to send you sample applications. There are already some in your system.  Have a look at the component WDR_TEST_SORT_TAB_PROP.  Also have a look at the documentation on table events:
    [http://help.sap.com/saphelp_nw70/helpdata/EN/2d/390e422dfcde2ce10000000a1550b0/frameset.htm|http://help.sap.com/saphelp_nw70/helpdata/EN/2d/390e422dfcde2ce10000000a1550b0/frameset.htm]

  • Question about printing and sorting files

    What I'm trying to do is read in a file of names (about a thousand) sort them using a sort alorithim then print out the sorted file of names, as well a separate chart with the number of compares and swaps . My Sort class has different sorting algorithims, like insertion, bubble etc. Everything I have now works fine. But the way its set up now I have to pick one algorithim at a time, then it sorts then prints the results like this:
    Bubble Sort
    Compares : 2016
    Swaps : 1052.
    Now if I want to choose anothert algorithim, I'll have to manualy do that then run Main again then apend the results to the output file. But I would like run Main once opening the file that needs to be sorted then run one algorithim, calc the results, then do that again for another algorithim calc the results, then when I'm finished with all the algorithims, print all the results at once to the output chart. This so the output will look better, and the user won't have repeatedly run the program to see and compare the results.
    Is this even possible, and if so, any ideas how?
    This is the main console, which put the names in a array list, then sorts
    them
    public class SortyFile {
         public static void main(String[] args) throws IOException{
               BufferedReader r = new BufferedReader(new FileReader("C:/Documents and Settings/Cougar/" +
                   "Desktop/names.txt"));
               PrintWriter Output_Chart
                    = new PrintWriter(new BufferedWriter(new FileWriter("C:/Documents and Settings/Cougar/" +
                      "Desktop/Output Chart2.txt" , true)));
               PrintWriter Output_Sorted_File
                    = new PrintWriter(new BufferedWriter(new FileWriter("C:/Documents and Settings/Cougar/" +
                           "Desktop/Sorted File2.txt")));
               ArrayList a = new ArrayList();
               String line = null;
               while ((line = r.readLine()) != null)
                    a.add(line);
                    Sort.bubbleSort(a);
                  Output_Chart.println("");
                  Output_Chart.println(Sort.algoname);
                  Output_Chart.println("");
                  Output_Chart.println("Compares :" + "   " + Sort.compares);
                  Output_Chart.println("Swaps :" + "      "  + Sort.swaps);
                  Output_Chart.println("");
                  for (int i=0; i<a.size(); i++){
                       Output_Sorted_File.println(a.get(i));
                       System.out.println(a.get(i));
               Output_Chart.close();
               Output_Sorted_File.close();
    This is the class with different sorting algorithims, the variable algoname is use for printing the header on the output chart.
    public class Sort {
        static int swaps = 0;
        static int compares = 0;
        static String algoname;  // name for the algorithim
        public static void swap(List data, int least, int i) {
              Object tmp = data.get(least);
              data.set(least, data.get(i));
              data.set(i, tmp);
         public static void bubbleSort(List data)
            for (int i = 0; i < data.size(); i++)
                for(int j = i+1; j < data.size(); j++)
                    Comparable current = (Comparable) data.get(j);
                    Comparable previous = (Comparable) data.get(i);
                    compares++;
                    if (current.compareTo(previous) < 0)
                        data.set(j, previous);
                        data.set(i, current);
                        swaps++;
            algoname = "Bubble Sort"; 
          public static void selectionSort (List data)
               int i,j, least;
               final int size = data.size();
               for (i = 0; i < size - 1; i++)
                  for (j = i+1, least = i; j < size; j++)
                       compares++;     
                 if (((((Comparable) (data.get(j))).compareTo(data.get(least)))) < 0)
                      least = j;
                      swap(data,least,i);
                      swaps++;
               algoname = "Selection Sort";
          public static void insertionSort (List data)
                 Comparable tmp;
              int i, j;
                 for(i = 1; i < data.size(); i++)
                      tmp =  (Comparable)data.get(i);
                       for(j = i; (j > 0) && (tmp.compareTo(data.get(j - 1)) < 0) ; j--){
                       compares++;
                       data.set(j, data.get(j - 1))  ;
                       data.set(j, tmp)  ;
                      swaps++;
                 algoname = "Insertion Sort";
    }

    Maybe Im misunderstanding your question, but couldnt
    you just run the bubbleSort() method, then the
    insertionSort() method, and so on? You would do this
    in your main method.Yeah I tried that but for odd reason I get this for the results
    Bubble Sort
    Compares : 2016
    Swaps : 1052
    Selection Sort
    Compares : 2016
    Swaps : 1052
    The results for both algorthims are exactly the same.

  • Simple VB macro to lock filters and sort excel option

    Hi gurus,
    do you have the solution via a macro to lock the possibility for the user to use filter or sort excel function in a manual planning.
    of course users can still create new lines use BPs filters...
    Thanks
    Cyril

    Hello Cyril,
    the following article should help:
    http://support.microsoft.com/kb/830502
    Regards,
    Marc
    SAP Techology RIG

  • How can I save a named filter and sorting for later use?

    I regularly do several different complex filtering and sorting on large tables. I did not find a way to save them for later one-click reuse. So I always have to do it again, which is time-consuming and error-prone. Hoped to get a solution by AppleScript, but filter and sort is not accessible by scripting.
    Is there a way or does Apple have it on it´s agenda for future versions of Numbers? 

    Hi Jan,
    filter and sort is not accessible by scripting.
    There is some support for sort (and less for filter) in Numbers 3.
    Table has a filtered property.
    And you can sort.
    A sort example can be found at https://iworkautomation.com/numbers/table-sort.html.
    Not sure if this will be sufficient to handle your needs, but just wanted to point out there is some scripting support.
    SG

  • Filter and sorter Problem

    Hi All
    hope someone can help me in this issue.
    if i build a list view from a table the filters and sorter are working fine, but if i build it using a recordset i get a page has this on it:
    Connection Interrupted
    The document contains no data.
    The network link was interrupted while negotiating a connection. Please try again.
    am i missing something in here ?!?!?
    here is the code for my page..
    http://twayns.150m.com/
    thnx

    -------
    but is ther any reason why the Site Root does not work?
    ADDT (and also DW´s own rudimentary PHP server behaviours) does require this setting for loading "related" files which are relative to the current document -- blame it on the "internal design" if you like, but that´s how it works ;-)
    but when try to filter using any data i got the message (underneath the menus): the table is empty or the filter is too restrictive!!!
    this means that filtering the table didn´t return any records for a reason which ADDT just doesn´t know, that´s why you´re getting this general message returned.
    If you´d like to change this message to something more meaningful like "No records found, please try with another filter setting", open the file "includes/resources/NXT.res.php" and change the line...
    'The table is empty or the filter you\'ve selected is too restrictive.' => 'The table is empty or the filter you\'ve selected is too restrictive.',
    ...to...
    'The table is empty or the filter you\'ve selected is too restrictive.' => 'No records found, please try with another filter setting.',
    Rule of thumb when editing ADDT´s "language files" which are all assembled in that "resources" folder: Only change the text string that´s displayed *after* the => sign, and always make sure not to accidently delete the surrounding ''
    Cheers,
    Günter Schenk
    Adobe Community Expert, Dreamweaver

  • Filter and sorting on table when getting data through store proc

    Hi All,
    I am using JDeveloper 11g and trying to implement a table which gets its data from a result set returned by a store procedure. The store procedure is using joins to fetch data from multiple oracle tables. I am able to display the data by binding result set element to each columns of ADF table, but sorting and filtering is not working on this, I have checked the chek box while creating table to make it sortable and filtering.
    Please help on this issue. How can we implement filtering and sorting in this case?
    Thanks in advance
    Saurabh agarwal

    Hi,
    I use managed bean directly to access data. My back end returns me a map with the values and these values are then mapped to columns.
    Can you please suggest me any link or example where this model supporting filter is used.
    Thanks
    Saurabh

  • IPhoto Questions:  Merge and Sort;  Cropping;  Collage

    Hello,
         I have some iPhoto questions:
         (1)  I have several different photos from different sources of my son's wedding.  I have merged the photos into one album and sorted them by date in iPhoto, but they are still showing all over the place.  How do I merge/sort them so that they all show in chronological/date & time order?
         (2)  I can only crop in square or rectangular shape.  Does iPhoto have a way of cropping using different shapes like heart, circle, triangle, etc?
         (3)  I cannot seem to find a way to create a collage in iPhoto where I can put 2 or more photos in one frame.  Is there a way for iPhoto to do this?
         I am not sure if these are iPhoto limitations or I need an upgrade to a version that can do all these?
    Thanks...

    As it merges the libraries iphoto library manager will ask you what you want to do with duplicates. However, remember files with different sizes are not duplicates. Also importing one library to another is not a good idea. You'll get a mess of different versions of files treated as new imports, so that's no way to merge.

  • How to access sort direction and filter value of columns?  Can I catch the 'filtered' or 'sorted' event?

    We have some columns being added to a table.  We have set the sortProperty and the filterProperty on each of our columns.
    This allows us to both filter and sort.
    We want to be able to access the columns filter value and sort value after the fact.  Can we access the table and then the columns and then a columns properties to find these two items?  How can I access the sort direction and filter value of columns?
    We would also like to store the filter value and the sort direction, and re-apply them to the grid if they have been set in the past.  How can we dynamically set the filter value and sort direction of a column?
    Can I catch or view the 'filtered' or 'sorted' event?  We would like to look at the event that occurs when someone sorts or filters a column.  Where can I see this event or where can i tie into it, without overwriting the base function?

    Hey everyone,
    Just wanted to share how I implemented this:
    Attach a sort event handler to table - statusReportTable.attachSort(SortEventHandler);
    In this event handler, grab the sort order and sorted column name then set cookies with this info
    function SortEventHandler(eventData)
        var sortOrder = eventData.mParameters.sortOrder;
        var columnName = eventData.mParameters.column.mProperties.sortProperty;
        SetCookie(sortDirectionCookieName, sortOrder, tenYears);
        SetCookie(sortedColumnCookieName, columnName, tenYears);
    Added sortProperty and filterProperty to each column definition:
    sortProperty: "ColName", filterProperty: "ColName",
    When i fill the grid with data, i check my cookies to see if a value exists, and if so we apply this sort:
    function FindAndSortColumnByName(columnName, sortDirection (true or false))
        var columns = sap.ui.getCore().byId('statusReportTable').getColumns();
        var columnCount = columns.length;
        for(var i = 0; i < columnCount; i ++)
            if(columns[i].mProperties.sortProperty == columnName)
                columns[i].sort(sortDirection);

  • Help needed for storing and sorting objects.

    Hello
    I have an assignment and it is to create a guessing game, here is the question,
    In this assignment you are to write a game where a user or the computer is to guess a random
    number between 1 and 1000. The program should for example read a guess from the keyboard, and
    print whether the guess was too high, too low or correct. When the user has guessed the correct
    number, the program is to print the number of guesses made.
    The project must contain a class called Game, which has only one public method. The method must
    be called start(), and, when run it starts the game. The game continues until the user chooses to
    quit, either at the end of a game by answering no to the question or by typing 'quit' instead of a
    guess. After each game has been played, the program is to ask the user for a name and insert this
    together with the number of guesses into a high score list. When a game is started the program
    should print the entire high score list, which must be sorted with the least number of guesses first
    and the most last. Note, the list must be kept as long as the game-object is alive!
    each score also
    consists of the game time. In case there are two high scores with the same number of guesses, the
    game time should decide which is better. The game time starts when the first guess is entered and
    stops when the correct guess has been made. There should also be input checks in the program so
    that it is impossible to input something wrong, i.e. it should be impossible to write an non-numeric
    value then we are guessing a number, the only allowed answers for a yes/no question is yes or no,
    every other input should yield an error message an the question should be printed again.
    I understand how to code most of it, except I am not sure how to store the playerName, playerScore, playerTime and then sort that accordingly.
    I came across hashmaps, but that wont work as the data values can be the same for score.
    Is it only one object of lets say a highScore class, and each time the game finishes, it enters the values into an arrayList, I still dont understand how I can sort the array all at once.
    Should it be sorted once for score, then another array created and sorted again, I dont get it I am confused.
    Please help clarify this.

    Implode wrote:
    We had the arrayList/collections lecture today.
    I asked the teacher about sorting objects and he started explaining hashmaps and then he mentioned another thing which we will only be learning next term, I'm sure we must only use what we have learned.
    How exactly can this be done. I have asked a few questions in the post already.
    ThanksWell, there was probably a gap in the communication. Hash maps (or hash tables, etc.) are instance of Map. Those are used to locate a value by its unique key. Generally, to speed up access, you implement a hashing function (this will be explained hopefully in class). Think of name-value pairs that are stored where the name is unique.
    Contrast this with items that are sorted. Any List can be sorted because its elements are ordered. An ArrayList is ordered, generally, by the order you inserted the elements. However, any List can be given its own ordering via Comparable or Comparator. You can't do this with an ordinary Map. The purpose of a Map is speedy access to the name-value pairs, not sorting. The List likewise has different purposes, advantages, disadvantages, etc. List can be sorted.
    A Map is generally similar to a Set. A Set is a vanilla collection that guarnatees uniqueness of each element (note, not name-value pairs, but simple elements). There is one concrete class of Map that can be sorted, TreeMap, but I doubt your professor was referring to that. The values or the keys can be returned from the Map and sorted separately, but again, I doubt he was referring to that.
    Take a look at the Collections tutorial here on this site or Google one. It is fairly straightforward. Just keep in mind that things (generally) break down into Set, Map and List. There are combinations of these and different flavors (e.g., Queue, LinkedHashMap, etc.) But if you can learn how those three differ, you will go a long way towards understanding collections.
    (Oh, and be sure to study up on iterators.)
    - Saish

  • Sort an ArrayList

    On the below code, how would i sort the ArrayList 'inv' by the 3rd element from greatest to smallest number.
    I.E.: 30, 22, 85, 75, 40, 45
    StoreInfo si = new StoreInfo();
            ArrayList sup = new ArrayList();
            ArrayList inv = new ArrayList();
            Supplier s = new Supplier("Hills", "777-123-2222");      
            Supplier s1 = new Supplier("Bantam", "430-126-0978");
            Supplier s2 = new Supplier("Time, Inc.", "967-534-7676");
            Supplier s3 = new Supplier("Starbucks", "897-888-4534");
            Supplier s4 = new Supplier("Prentice Hall", "678-555-9876");
            sup.add(s);
            sup.add(s1);
            sup.add(s2);
            sup.add(s3);
            sup.add(s4);
            inv.add(new Book(s1, "Java for Fun", 30, 45.50, "Wolff"));
            inv.add(new Book(s4,"Databases for Dummies", 22, 65.50, "Riggins"));
            inv.add(new Magazine(s2, "Time", 85, 6.00, new Day(2004,3,5)));
            inv.add(new Magazine(s2,"Sports Illustrated", 75, 5.50, new Day(2004,2,20)));
            inv.add(new Coffee(s,"Breakfast Jolt",40,9.95,"2 pounds"));
            inv.add(new Coffee(s3,"Afternoon Snooze",45,12.95, "1 pound"));

    ok, i read that entire tutorial twice even still a few more questions.
    here is my compareTo method implementing the comparable:
    public int compareTo(Object obj) throws ClassCastException {
              if (!(obj instanceof Inventory))
                throw new ClassCastException("An Inventory object expected.");
              int anotherInv = ((Inventory) obj).getNumInStock();
              return this.numInStock - anotherInv;
         }and this is where i use it
    public void sortPrint(ArrayList inventory)
             Collections.sort(inventory);
             int size= inventory.size();
             for (int i=0; i<size; i++)
                  Inventory inv = (Inventory) inventory.get(i);
                  inv.toString();
        }from what i got from that turorial, you use the Collections call to use the compareTo method?? is this true, if so why?
    here is the error i get:
    java.lang.ClassCastException
         at java.util.Arrays.mergeSort(Arrays.java:1122)
         at java.util.Arrays.sort(Arrays.java:1073)
         at java.util.Collections.sort(Collections.java:109)
         at cornerBookStore.StoreInfo.sortPrint(StoreInfo.java:336)
         at cornerBookStore.CornerBookStore.main(CornerBookStore.java:91)
    Exception in thread "main"
    thanks for your time!

  • Questions on photos and storage

    I have a few questions about photos and storage... If you can just answer one of these, that's fine and thanks for the help!
    How do I see how much space my iPhoto photos are taking on my hardrive?
    I have Time machine which backs up, but concerned that I'm getting too many pictures.  When I do "Get Info" on the hardrive it says 640GB Capacity with 254GB used. I'm assuming that includes all my photos, and that Time machine only backs up and is not the active storage for those photos?
    What is advisable for available GB space on this size computer?
    I have my photos on the hardrive and the time machine, is it also advised to have in a cloud-based storage system to be safe? Or some other place.  Just checking what others do with this.

    1 - it is a really good idea to start new threads with new questions - threadjacking a year old solved thread on a totally different subject will not provide the best coverage and the best answers
    2 - Do NOT uncheck the option to copy imported items to the iPhoto library - it is a really, really bad idea that will create many problems for yo and has no advantages of any sort - see the user tip on file management in iPhoto for more details - iPhoto and File Management
    3 - take the time to learn how to use iPhoto and the concept of using a database for management photos rather than a file based system like you are used to - it is much different and much more powerful - but there is a learning curve and a different thought process
    4 - yes you can always export anything or everything from iPhoto for use on any other system - see the user tip on exporting for details - Exporting From iPhoto
    5 - always remember that you never access your photos directly - iPhoto totally replaces the finder for managing your photos - see the user tip on accessing photos for more details - How to Access Files in iPhoto
    LN

  • Issue with value of  transient attribute after filtering or sorting a table

    Hi guys,
      i'm using jdev 11.1.1.4.0 .
      i've the use case :
             - a table with a column containing a checkbox to mark the selection of  a row
    <af:column align="center" sortProperty="TemIsChosen" filterable="true"
    sortable="true" id="c6">
    <af:selectBooleanCheckbox value="#{row.bindings.TemIsChosen.inputValue}" autoSubmit="true"
    shortDesc="#{bindings.ServersIndicTempVVO.hints.TemIsChosen.tooltip}"
    id="sbc1"
    valueChangeListener="#{backing_initIndicatorsTemp.onSelectTemp}"/>
    </af:column>
             - i select one or more rows with checkboxes
             - if i filter  or sort the table, the selection of the checkboxes reset to not selected (value false by default).
         I understand that for the framework, it's a normal behavior because for filtering or sorting , it re-executes the query from database. And transient attribute is not persistent, so it goes back to the default initial value "false".
         What i would appreciate, it's that filtering or sorting has no effect on the value of the transient attribute, ie end user selection remains.
          I tried to modify query mode of the ViewObject to filter with in-memory data. It works fine but if you reset filter inputs you can't retrieve correct RowSet. Only new RowSet is stored, old is lost.
           So  now it's the filtering feature that doesn't work as expected.
       How can i implement  my use case withouth the troubles i've described.
    Best regards,
    David

    Hi Frank,
       no it's a view object level attribute inside a read-only view object.
      The view object doesn't use any entity.
      Here is the definition of the attribute in the xml file of the VO, if can help you :
    <ViewAttribute
        Name="TemIsChosen"
        IsSelected="false"
        IsPersistent="false"
        PrecisionRule="true"
        Type="java.lang.Boolean"
        ColumnType="BIT"
        AliasName="VIEW_ATTR"
        SQLType="BIT"
        Passivate="true">
        <Properties>
          <SchemaBasedProperties>
            <TOOLTIP
              ResId="ADD"/>
            <DISPLAYWIDTH
              Value="50"/>
          </SchemaBasedProperties>
        </Properties>
      </ViewAttribute>
    David

  • Adding new value in Pick list and sorted logic on basis of new value.

    Hi All,
    I have a requirement where I have to add a new value in seeded OAMessageBean and sort the page contents on basis of selected value.
    I see in about this page and found out that no VO is attached with this field.
    I assume that it attached somewhere in controller and tried to find out there but cannot able to find it there.Is there any way to find the VO which is attached to this bean?
    Also how to add a new values in this seeded picklist as I can able to get handle to OAMessageBean in custom controller.
    Please Help.
    Regards,
    889254

    Hi Peddi,
    Thanks a lot for your reply,
    I tried to open that page in jdeveloper but I dont see any choice bean on the page.Also tried to open CO attached to this page but no clue.As I am able to the get handle of this choicebean in controller.Is there any way I can find out which VO attached to this choiceBean.
    I tried using below depricated method and it is returning null
    messageField.getListViewObject();
    My another question is Can we add new value to choice bean In CO.
    I tried to add it by below methods but these are not reflecting in the application.
    messageField.addOption("TEMP");
    messageField.addIndexedChild("TEMP");
    Regards,
    889254

  • Russian and English combined Index Group Title and sort order

    How should I create the combined index Group Title and sort order in Russian and Greek documentations?

    The final product one Russian manual which contains some English Index marker ...
    And what is the problem?
    You can control the sorting by placing a [...] tag in the Marker Text, such as:
    [Сплайн] Spline
    The term(s) in the brackets are used only for sort. What appears in the Index is the following text.
    Or you can just edit the Marker Text.
    But it sounds like there might be more than one question here, re: Group Titles.

Maybe you are looking for

  • Hot to copy text from a Popup Windows in SAP CRM 7.0?

    Hi guys, we want to copy text from a POPUP Windows but you cannot highlighttext there. We've tried with "Popup to Decide List" and "Popup for Reuse components". Do you know if is possible to copy text from a POP-UP Windows in CRM WUI 7.0? We also hav

  • Email iphoto slide show

    How do I send an iphoto slide show with music via email?

  • How to run a jms-class as a stand-alone java-Programm???

    Hi, I have another little question concerning jms. The jms programs I have written so far had to be executed as application clients using the appclient-tool. I asked myself, if it is possible to run a class that uses jms like a normal java-Programm w

  • Reverse function for Logic X

    I'm trying to use the reverse function for an audio file. when I open the audio file editor, there is no "Functions" pull down menu. how do I find it? thanks!

  • MicroCell not working after download of ios5

    Since downloading ios5 can't connect to MicroCell no matter what I try. Been on the phone with AT&T all morning.