Iterate through 2 collections

Hi,
I have two collections. One collection (A) has "Item" objects. Next collection (B) has Strings, these Strings are ids of Items.
class Item{
    String id;
    String ....
}All the ids in Collection B matches with Item object's id field in Collection A.
ie: Collection B does not have a single id where you can't find an item object in Collection A.
So Collection A is larger than Collection B.
I have to iterate through the Collections and I want to separate the Items in Collection A into separate collections depending on whether Item's id was found in Collection B or not.
My question is; which one is good in Big-O.
1. for(Item i: A){
   for(String id: B){
}2. for(String id: B){
   for(Item i: A){
}Could you explain pls?

So, do you want someone to agree on ejp's explanation? Shall I repeat?
|A| = N
|B| = M
1. f.a. a in A: (f.a. b in B: b.id = a => retain(b))
2. f.a. b in B: (f.a. a in A: b.id = a => retain(b))
Without any "optimization" you get O(N*M) in both cases.
In both cases, you could break the inner loop once you found a match. I'd say that WLOG one will have to scan half the inner collection in average to find a match, so we have:
1. O(A * B/2)
2. O(B * A/2)
Which, obviously, is the same.
If one of the collections is sorted, the sorted one should be the inner loop, as it only takes O(log2(X)) instead O(X/2) to search for a match.
If one of the collections is hashed, the hashed one should be the inner loop, as it takes O(1) to search for a match (depending on the distribution of hash values).

Similar Messages

  • Iterate Through Lists Instead of Document Libraries, Or both

    System Info: SharePoint 2010 Enterprise w DEC 2013 CU. 2 WFEs (load balanced), App Server, SSRS Server, Dedicated CA Server (All running Win 2k8 R2).
    Background:I have a large (5,000 user) application that is completely customized on top of SP2010. I am the admin, and have been on the team for many years. Previously, we had a development team,
    but client has scaled costs back, and now its just me on the technical side. We have a Web app that houses multiple Site Collections, and each site collection has various subsites.
    My Problem: We have increased the LVT to 10k items (system has plenty of HP, although we do see performance degradation). Each subsite in the Site Collection holds data specific to an organization
    wtihin the Line of Business. There are two lists that frequently approach the 10k mark, and we have mitigation steps in place (essentially, we just create a new SubSite for them once they reach 10k). What I need is a single script that will traverse ALL subsites
    and return a count of their lists, perhaps I can work a couple of if statements in there to have specific data written to a SP List (if count is greater than 5000), and other wise everything gets written to the output file.
    I am trying to iterate through all lists and return a count of folders + items ... The script below works just fine, but it goes through Document Libraries only (per the baseType eq tag).
    I've tried changing baseType from DocumentLibrary to GenericList, but I continually get an error.
    I've also removed the where baseType = DocLib clause completely, and this has the desired results (all lists and doclibs are listed), except the 'WebUrl' field in the csv output is blank.
    Any thoughts on how I can make a small tweak to this script to get my desired results?
    Start-SPAssignment -Global
    $OutputFile ="D:\folder\DocCount3.csv"
    $results = @()
    $webApps = Get-SPWebApplication http://WebAppURL
    foreach($webApp in $webApps)
    foreach($siteColl in $webApp.Sites)
    foreach($web in $siteColl.AllWebs)
    $webUrl = $web.url
    $docLibs = $web.Lists | Where-Object {$_.baseType -eq "DocumentLibrary"}
    $docLibs | Add-Member -MemberType ScriptProperty -Name WebUrl -Value {$webUrl}
    $results += ($docLibs | Select-Object -Property WebUrl, Title, ItemCount)
    $results | Export-Csv -Path $OutputFile -NoTypeInformation
    Stop-SPAssignment –Global

    You guys won't believe this ... But, the script actually works as intended if I change the baseType tag to "GenericList"... I had been getting errors (about 14 of them) through PowerShell and
    assuming the script didn't process, but after looking at the output CSV, it seems that everything worked properly. I think the 14 errors MAY have been corrupted sites (or something?) as it gives me NullValueNotAllowed when trying to "Add-Member" and points
    to $WebUrl as being null.
    Next up -- working on getting this script to write specific objects to a SP list!

  • How to split a string into tokens and iterate through the tokens

    Guys,
    I want to split a string like 'Value1#Value2' using the delimiter #.
    I want the tokens to be populated in a array-like (or any other convenient structure) so that I can iterate through them in a stored procedure. (and not just print them out)
    I got a function on this link,
    http://www.orafaq.com/forum/t/11692/0/
    which returns a VARRAY. Can anybody help me how to iterate over the VARRAY, or suggest a different alternative to the split please ?
    Thanks.

    RTFM: http://download-uk.oracle.com/docs/cd/B19306_01/appdev.102/b14261/collections.htm#sthref1146
    or
    http://www.oracle-base.com/articles/8i/Collections8i.php

  • Iterate through selected characters

    Hi guys and girls!
    Has anybody a code snippet to show me how to iterate through the selected text (not the frame!, not the words, only the selected chars) and make any change on the characterAttributes (size, color, etc.)?
    Deeper into it:
    In the property "app.activeDocument.selection" usually the selected objects are stored as an array. Now when I select characters in a textframe (or TextPath, whatever) there is a [Textrange] in it.
    I already tried some combinations like this snippet underneath but I still get errors, that selectedChars[i] is undefined.
    FYI: I'm on Illustrator CS4, Mac OS X, Javascript
    var selectedChars = app.activeDocument.selection.characters;
    for (i = 0; i < selectedChars.length; i++ ){                           
         selectedChars[i].characterAttributes.fillColor = myNewCMYKColor;
    I hope I have gathered all relevant information. If not, please do not kill me and just ask back
    So has anybody a smart hint for me?
    Thanks a lot in advance!

    Here's a Change Size script that I found in my collection that somebody posted severat years ago. I'm sorry I don't remember who it was to give proper credit.
    #target illustrator
    // change size of paragraph text
    //$.bp();
    ChangeSize();
    function ChangeSize()
        selectedItems = selection;
        // check to make sure something is selected.
        if (selectedItems.length == 0)
            alert("Nothing is selected");
            return;
        endIndex = selectedItems.length;
        for (index = 0; index < endIndex; index++)
            pageObject = selectedItems[index];
            pageItemType = pageObject.typename;
            if (pageItemType == "TextFrame")
                // get the paragraphs from the selection.
                theTextRange = pageObject.textRange;
                paraTextRange = theTextRange.paragraphs;           
                numParagraphs = paraTextRange.length;
                for (i = 0 ; i < numParagraphs ; i++)
                    aParagraph = paraTextRange[i];
                    charTextRange = aParagraph.characters;
                    charCount = charTextRange.length;
                    if (charCount > 1)
                        end = charCount;
                        fontSizeChanger = 14/end;
                        currentFontSize = 18;
                        for (j = 0 ; j < end; j++)
                            theChar = charTextRange[j];
                            theChar.size = currentFontSize;  
                            currentFontSize = currentFontSize - fontSizeChanger;
    and here's the output.
    You should be able to go from there.

  • Iterate through HashMap ?

    Hello,
    is it possible to iterate through a Java HashMap somehow?
    Or is there any other iterable data structure i could use (I need to get objects from the data structure by using an integer value as key ) ?
    thanks!

    It depends...
    Simple answer: you can use keySet() or values() to get respectively a Set or a Collection, then you iterate on them (using iterator()).
    But you have no guarantee on the order of iteration.
    Now, a data structure using an integer as key is commonly called... an array! Half joking, it works well if these integers are consecutive or of limited range.
    If you need to iterate in increasing key values, use a TreeMap.

  • Iterate through a list containing Map items using struts

    Hi friends,
    I have a small problem. I want to iterate through a list of items, using struts.
    The list actually contains map structres for example:
    list(0)
         map(..key..value..)
         map(..key..value..)
         map(..key..value..)
    list(1)
         map(..key..value..)
         map(..key..value..)
         map(..key..value..)
    list(2)
         map(..key..value..)
         map(..key..value..)
         map(..key..value..)can I use <logic:iterate/> for this? if yes how? Because I have used this tag for list containing bean objects not Map.
    Any suggestions are much appreciated.
    Thanks,
    Vishal

    Normally, each object exposed by the iterate tag is an element of the underlying collection you are iterating over. However, if you iterate over a Map, the exposed object is of type Map.Entry that has two properties:
    key - The key under which this item is stored in the underlying Map.
    value - The value that corresponds to this key.
    So, if you wish to iterate over the values of a Hashtable, you would implement code like the following:
    <logic:iterate id="element" name="myhashtable">
    Next element is <bean:write name="element" property="value"/>
    </logic:iterate>
    Best Regards
    Maruthi

  • Iterate through all the records in a table using Java API

    Hi All,
    What is the easiest way to iterate through all the records in a given table using Java API? I cannot find any methods that will return all records in a table and the only way I can use is to perform a free form search with a condition that is always true. The code works but is pretty ugly. Is there an alternative to this approach?
    Thanks!
    Kenny

    Hi Kenny,
    You can construct a new Search object with your table's code name, a new ResultSetDefinition object for your table and just execute this search using the GetResultSet method of CatalogData.
    Please look at the following code:
    Search search = new Search(<code name of your table>);
    ResultSetDefinition rsd = new ResultSetDefinition(<code name of your table>);
    rsd.AddField<code name of a field>);
    rsd.AddField(<code name of a field>);
    String sortField = <code name of your sort field>;
    boolean sortAscending = true;
    int page = 0; //page number
    A2iResultSet rs = <your CatalogData object>.GetResultSet(search, rsd, sortField, sortAscending, page);
    for (int i = 0; i < rs.GetRecordCount(); i++)
        Value fieldValue = rs.GetValueAt(i, <code name of a field>);
    Hope this helps,
    Nir
    PS - I really recommend you to start using the new API, as it is much more efficient and straight-forward.

  • Best way to iterate through multiple variables?

    I need to iterate through three different variables (arrays), and was wondering what the best way to do this would be? I am more familiar with C than I am with LabVIEW at this point, but am getting up to speed on LabVIEW pretty quickly. Normally in C, I would just create three nested loops, but I am wondering if this is the best method in LabVIEW or not. I could use a state machine I think, which would give me some flexibility in re-arranging the order of iteration or adding or subtracting variables easier than working with nested loops I think...anyway, I'm open to suggestions.

    R.Gibson wrote:
    I need to iterate through three different variables (arrays), and was wondering what the best way to do this would be?
    Arrays are not "variables". can you be a bit more specific.
    R.Gibson wrote:
    I could use a state machine I think, which would give me some flexibility in re-arranging the order of iteration or adding or subtracting variables easier than working with nested loops.
     Why does the order matter? Rearranging in what way? If you do autoindexing, it will just iterate over all elements until it runs out of elements.
    ... And again, what do you mean by "variables"?
    It would help if you could show us a VI containing some typical input data in controls (make current value default, save) and explain what kind of output you expect.
    LabVIEW Champion . Do more with less code and in less time .

  • Iterate through string column of data that is a varchar2 (2000)

    Hi,
    My question is how to iterate through the data by selecting the first 120 bytes of the column writing that to a UTL_FILE, then selecting the next 120 bytes to write that to the UTL_FILE as well until there is no more data. I am having a problem getting the second 120 and so on. The column of data is just text.
    Thanks any help is greatly appreciated.

    I'm sure there is a shorter or more elegant solution, but this is from a quick function I wrote a while back that might give you an example-
    -- Declare variables
            v_msg VARCHAR2(2000) := 'whatever your message is';
            v_pos NUMBER := 1;
            v_len NUMBER := 0;
            v_max_len NUMBER := 120;  
            v_yourstring VARCHAR2(150);
    -- Iterate in the body of your procedure
               v_len := length(v_msg);
                WHILE v_len > 0
                LOOP
                    v_yourstring :=  (substr(v_msg, v_pos, v_max_len));
                    -- do whatever you need to do with first 120 characters
                    v_pos := v_pos + v_max_len; 
                    v_len := v_len - v_max_len;                                             
                END LOOP;

  • For loop to iterate through temp table in store procedure in pl/sql

    Hi,
    how to create For loop to iterate through the temporary table in the store procedure?

    Neha RK wrote:
    hi,
    its not working , i need to check each record of table and do some task using if else loop inside that for..
    if not possible to loop each row of table using for then how to use while loop.
    please helpWhat's not working? We haven't got psychic powers so we can't see the code you say isn't working.
    Please provide more information like create table statements, insert statements with test data, the code you've tried
    and the output you are expecting from the input data.
    Read {message:id=9360002} and follow the advice there.

  • Iterate through XML find the missing element and prepare report

    Hi',
    I am reading a XML and if the ID is missing in that XML, then I have to make a report which can be send by mail
    by telling that these are the name for which ID is not present.
    I am able to iterate through the records and check if the ID is not present and pick the names for that,
    What I am not getting is how to put these names in a proper format.
    Like if I copy then each time the variable will be overwritten, if I use a append then a full new XML gets created.
    Please tell me how I can make a proper report.
    Thanks
    Yatan
    <Records>
    <Employee>
    <name>Yatan</name>
    <ID></ID>
    <Age>28</Age>
    </Employee>
    <Employee>
    <name>Yagya</name>
    <ID>101</ID>
    <Age>27</Age>
    </Employee><Employee>
    <name>Yugansh</name>
    <ID></ID>
    <Age>24</Age>
    </Employee>
    </Records>

    What about you do a XSLT transformation to get the email content in HTML format... That would avoid you to iterate through your XML...
    The template would be like this:
    <xsl:template match="/">
            <h2>These are the employees without ID</h2>
            <xsl:for-each select="/Records/Employee[ID = '']">
                <xsl:value-of select="name"/>
                <BR/>
            </xsl:for-each>
    </xsl:template>This is just a sample, syntax was not verified, but I think you'll get the idea...
    Please let me know if this was helpful...
    Cheers,
    Vlad

  • Iterate through all documents

    Hi,
    We have a container which contains *1 million* documents, each of which has size 5K. Container type is wholedocument. We need to iterate through all document regualrly using container.getAllDocuments(containerTxn, DBXML_LAZY_DOCS | DBXML_NO_INDEX_NODES). For each document, we will perform a xpath query in xml document in memory.
    The problem here is about whether we should use transaction. If transaction is used, getAllDocuments will report "Lock table is out of available lock entries" error when it scan about 9383 ducuments. Here are lock setting:
    envp->set_lk_max_lockers(6000);
    envp->set_lk_max_locks(6000);
    envp->set_lk_max_objects(8000);
    We have 1 million documents, it is impossible to set lock object to 1 million.
    My questions:
    (1) Is this normal? If so, why performing a dbxml query on the container doesn't cause such an error. I believe dbxml query has to iterate all of documents too.
    (2) Is it possible to use a seek position for getAllDocuments? Thus we can commit transaction every iterating 1000 documents, and then continue the iteration from the last seek position.
    (3) if we don't use transaction to call getAllDocuments, what possible problems will happen? Other threads are using transaction to read/update the documents.
    Thanks.
    -Yuan

    Yuan,
    The quickest thing to try is to add the flag DB_READ_COMMITTED to getAllDocuments(). That may reduce the number of locks you need. While you may not be able to set the various lock parameters to 1 million, you should set them much larger than you have now (e.g. 50k - 100k) for this sort of operation.
    Not using transactions at all can lead to inconsistent data mostly related to index consistency with document content. Depending on the nature of your updates it may be safe. You could get stray exceptions but nothing should crash. E.g. if you are only adding/removing documents you are probably safe without transactions; although you might iterate to a document that's been removed so you'll see an exception which would have to be ignored. I'm not 100% certain this will work well but if you can test it in a high-update environment and see no issues that will tell you. The read side will not interfere with the updates.
    As for "seeking" if you look under the covers getAllDocuments() is really just a wrapper for an index lookup on the name index. The XmlIndexLookup API is quite flexible in terms of returning ranges. If you want to look into returning ranges of documents, do this:
    1. look at the code in XmlContainer.cpp in the function "getDocs()". It uses XmlIndexLookup to perform the operation.
    2. look at the XmlIndexLookup API to figure out how to turn the lookup into a range lookup vs looking up ALL items in the index
    Using XmlIndexLookup and tracking the name of your last-used document you can easily ask for all documents "higher" than that one. Further, if you know how your documents are named lexicographically you can give it a maximum as well if you wanted, but given that you can set your XmlQueryContext to be lazy you can simply iterate N times to get the next N documents without paying a penalty retrieving any documents you don't need.
    For the sort of thing you are doing I highly recommend using XmlIndexLookup directly (with or without transactions) to get the flexibility you need. XmlContainer::getAllDocuments() is merely a "convenience" layer on that class.
    Regards,
    George

  • Iterate through RichTable with custom cells

    Hi.
    I create a RichTable by drag and drop a view in DataControls. View is from table xxx and table contains only one column, binding description field in the table.
    This description is shown in an OutputText UI component.
    Then, I add a column with a SelectOneRadio component (to check Yes/No).
    Finally, I add another column with an Input Text to write comments.
    So, when I click one button, I capture the action event and want to process table content. But, how can I iterate through this table?
    How can I get each row, and each cell in its row (each radio, each text)?
    My JDeveloper version is 11.1.1.7.0
    Thanks in advance. Best regards
    EDIT: _________Final solution_________
    Add two transient attributes and iterate the VO object is very easy.
    For the specific issue about radio button, add a switcher and bind the radio group with the transient attribute.

    Hi,
    You could do something like
                   <af:switcher id="s1" defaultFacet="input" facetName="#{row.type eq 0?'radio':'input'"}>
                    <f:facet name="input">
                        <af:inputText id="it2" value="#{row.answer.inputValue"}/>
                    </f:facet>
                    <f:facet name="radio">
                        <af:selectBooleanRadio id="sbr1" value="#[row.answer.inputValue"}/>
                    </f:facet>
                    </af:switcher>
    -Arun

  • Iterate through the child Objects in a components

    I have a custom component named myComp that has three TextInputs. And in the main application there is a button that adds this component dynamically to the VBox named myVBox, I would like to know how to iterate through the added components and show the text inside each of the TextInputs in an Alret box. I am pretty new to flex and I couldn't find any examples for it.
    Thanks,

    Sample code,
    Custom Component
    MyComp1.mxml
    <?xml version="1.0" encoding="utf-8"?>
    <mx:HBox xmlns:mx="http://www.adobe.com/2006/mxml">
         <mx:TextInput id="txt1" width="100" />
         <mx:TextInput id="txt2" width="100" />
         <mx:TextInput id="txt3" width="100" />
    </mx:HBox>
    Application
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application
         xmlns:mx="http://www.adobe.com/2006/mxml"
         layout="absolute"
         creationComplete="init()">
         <mx:Script>
              <![CDATA[
                   import mx.controls.Alert;
                   import com.MyComp1;
                   private function addComponent(event: MouseEvent): void {
                        var myComp1: MyComp1 = new MyComp1();
                        myVBox.addChild(myComp1);
                   private function getText(event: MouseEvent): void {
                        var alertMsg: String = "";
                        for (var i: int = 0; i < myVBox.getChildren().length; i++) {
                             if (myVBox.getChildAt(i) is MyComp1) {
                                  var myComp: MyComp1 = myVBox.getChildAt(i) as MyComp1;
                                  alertMsg += myComp.txt1.text + "\t" +
                                                 myComp.txt2.text + "\t" +
                                                 myComp.txt3.text + " \n"
                        Alert.show(alertMsg);
              ]]>
         </mx:Script>
         <mx:VBox width="100%" height="100%">
              <mx:Button label="Add Comp" click="addComponent(event)" />
              <mx:Button label="Get Value" click="getText(event)" />
              <mx:VBox id="myVBox" width="100%" height="95%">
              </mx:VBox>
         </mx:VBox>
    </mx:Application>
    Hope this helps you

  • How do I iterate through a subform structure ?

      I have subforms which have individual fields which I have to set access either open or protected.  Instead of listing each single field, is there a way I can use a for loop to iterate through the subform and set each field access as needed?

    That’s unfortunate because we aren’t using Acrobat/Reader to read the forms.  We’re using a product called FormStream Filler.  Anyway, I stumbled onto a technique used in a previous form here.  I don’t understand everything about it, but I was able to replace enough code to get it to work with my form.  Suffice to say it has a lot to do with nodes. 
    Thanks for  answering.

Maybe you are looking for