Solved

Creating a list from 2 list

Posted on 2011-09-06
33
581 Views
Last Modified: 2012-05-12
I have a program that is parsing selected objects.  Each object has a dataset attribute and a rev attribute.  So I am storing the results in 2 list.  

1st selection

data1 rev1

I am placing data1 in a list name datasetList and rev1 is going in to a list named revList.  
If there is another selection then it is placed the same way.  So at the end of the for loop I will have 2 list ( datasetList and revList).  I need to put them in to one list.  I am not sure how to create a list from 2 list.   Then I need to know how to make the 1 list global something like a package file, so that other classes will be able to access the values.
0
Comment
Question by:jkteater
  • 15
  • 12
  • 6
33 Comments
 
LVL 47

Expert Comment

by:for_yan
Comment Utility
You can create your custom class which will have two fikeds - dataset and revision and then make a set or ArrayList made uo of the instances iof your custom class
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
>> Each object has a dataset attribute and a rev attribute.  So I am storing the results in 2 list.  

Why are you not just making one list of each object?
0
 
LVL 47

Expert Comment

by:for_yan
Comment Utility
So you define your class:

class MyClass {
String data;
String rev:
MyClass(String s1, String s2){
data = s1;
rev = s2;
}
}

ArrayList <MyClass> ar = new ArrayList<MyClass>();

As you parse you create your objects and add them to ArrayList

ar.add(new MyClass(data,rev));

0
 
LVL 47

Expert Comment

by:for_yan
Comment Utility
You also want to define getMethods to get individual data and rev values from istance of MyClass and probably also eqials() method to know which pair of objects you consider identical

And this arraylist populated with your objects can be used anywhere in your porogranm - you can also have it sent as a paramerter, or serialized to sedn to some server process etc etc
0
 

Author Comment

by:jkteater
Comment Utility
Responding to CEHJ

Each dataset can have multiple revs.  They are not suppose to have more than one.  So it works like a check.  If Rev has more than one we terminate the program.  That is the reason I have a list for rev as well dataset.  Dataset has a list because the user can select more than one dataset.  That is the reason I have 2 list.  So now I need to create 1 list with the values from the 2 list.  Once I have the 1 list I worry more about making it a class.  

Thanks
0
 
LVL 47

Expert Comment

by:for_yan
Comment Utility
Maybe you could post a snippet of your code, so it would be more understandable what you want
0
 
LVL 47

Expert Comment

by:for_yan
Comment Utility
If your dataset and rev are both Strings (I'm guessing they are) and there is always one rev per dataset,
maybe you can combine two strings into one using some separator character (or even combination of characters)
 which cannot be part of either dataset or of rev and then you make a list of these combined strings
Ot maybe you want to make a HashMap of them - again taking into account that each datase has only one
rev It all depends how you want to use this data afterwards,
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
>>Dataset has a list because the user can select more than one dataset.

So the entity at the top of the tree is really 'User'?
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
It certainly sounds like that's the case. If multiple revs are possible for one dataset, then the first class below would represent the hierarchy, else the second (simpler) one
public class User {
	private Map<Dataset, List<Rev>> datasets;
}

public class User {
	private Map<Dataset, Rev> datasets;
}

Open in new window

0
 

Author Comment

by:jkteater
Comment Utility
Here is the code I am taking about
public class ediHandler extends AbstractHandler {
   private List<TCComponent>    revisionList;
   private List<TCComponent>    datasetList;
     
   public ediHandler() {
      // TODO Auto-generated constructor stub
   revisionList = new ArrayList<TCComponent>();
   datasetList = new ArrayList<TCComponent>();
   }
   
  
   @Override
   public Object execute(final ExecutionEvent event) throws ExecutionException {
      ISelection sel = HandlerUtil.getActiveWorkbenchWindow(event).getActivePage().getSelection();
      final StringBuilder objectsSelected = new StringBuilder();
      objectsSelected.append("Here are the objects selected:\n");

      if ((sel != null) && (sel instanceof IStructuredSelection)) {
	         IStructuredSelection structSelection = (IStructuredSelection) sel;
	         for (Iterator<?> iter = structSelection.iterator(); iter.hasNext();) {
	        	 AIFComponentContext element =  (AIFComponentContext) iter.next();
	        	 TCComponent selectedDataset = (TCComponent) element.getComponent();
	        	 TCComponent selectedDatasetType = selectedDataset.getTypeComponent();
	        	 TCComponent[] selectedRevisions;
				try {
					selectedRevisions = selectedDatasetType.getRelatedComponents("IMAN_specification");
					int size = selectedRevisions.length;
					System.out.println("size" + size + "\n");
					if (size == 1) {
		        	   revisionList.add(selectedRevisions[0]);	
		        	}
		            else {
		        		System.out.println("Terminate\n");
		        	    continue;
		        	}
					
					//revisionList.addAll(Arrays.asList(selectedRevisions));
				} 
				catch (TCException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	        	 /*TCComponent parentType =  selectedParent.getTypeComponent();*/
	        	
				
				datasetList.add(selectedDatasetType);
	            //Printing Results
	            //objectsSelected.append("Selected Type " + selectedType.toString() + "\n");
				//objectsSelected.append("Parent Type:  " + parentType.toString() + "\n");
		    }
	              
	         
      }

Open in new window

0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
Using my second class (see my initials in the source) that would go something like:
@Override
    public Object execute(final ExecutionEvent event) throws ExecutionException {
        ISelection sel = HandlerUtil.getActiveWorkbenchWindow(event)
                                    .getActivePage().getSelection();
        final StringBuilder objectsSelected = new StringBuilder();
        objectsSelected.append("Here are the objects selected:\n");

        if ((sel != null) && (sel instanceof IStructuredSelection)) {
            IStructuredSelection structSelection = (IStructuredSelection) sel;

	    //CEHJ
	    User user = new User();
            for (Iterator<?> iter = structSelection.iterator(); iter.hasNext();) {
                AIFComponentContext element = (AIFComponentContext) iter.next();
                TCComponent selectedDataset = (TCComponent) element.getComponent();
                TCComponent selectedDatasetType = selectedDataset.getTypeComponent();
                TCComponent[] selectedRevisions;

                try {
                    selectedRevisions = selectedDatasetType.getRelatedComponents(
                            "IMAN_specification");

                    int size = selectedRevisions.length;
                    System.out.println("size" + size + "\n");

		    if (size == 1) {
			//CEHJ
			user.datasets.put(selectedDataset, selectedRevisions[0]);
		    } else {
			System.out.println("Terminate\n");

			continue;
		    }

		    //revisionList.addAll(Arrays.asList(selectedRevisions));
		} catch (TCException e) {
		    // TODO Auto-generated catch block
		    e.printStackTrace();
		}

		/*TCComponent parentType =  selectedParent.getTypeComponent();*/
		datasetList.add(selectedDatasetType);

		//Printing Results
		//objectsSelected.append("Selected Type " + selectedType.toString() + "\n");
		//objectsSelected.append("Parent Type:  " + parentType.toString() + "\n");
	    }
	}
    }

Open in new window

0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
(Of course you'd have to make sure User got collected/processed appropriately)
0
 

Author Comment

by:jkteater
Comment Utility
I really think I have done a lousy job of explaining what I am trying to do.  

I have 2 ArrayList.

revisionList
datasetList

I need to make one list from the 2 called queueList.  I am not sure how to make list where it would be something like this

queueList[0] = revisionList[0], datasetList[0]
queueList[1]  = revisionList[1], datasetList[1]

Then I need to store the queueList where I can get to the values from other classes.  I will post what code I have and I will increase the points, because I really need to get this figured out.

0
 

Author Comment

by:jkteater
Comment Utility
package com.ediua.handlers;

import java.util.*;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.handlers.HandlerUtil;
import org.eclipse.swt.widgets.Display;

import com.teamcenter.rac.aif.kernel.AIFComponentContext;
import com.teamcenter.rac.kernel.TCComponent;
import com.teamcenter.rac.kernel.TCException;


public class ediHandler extends AbstractHandler {
   private List<TCComponent>    revisionList;
   private List<TCComponent>    datasetList;
     
   public ediHandler() {
      // TODO Auto-generated constructor stub
   revisionList = new ArrayList<TCComponent>();
   datasetList = new ArrayList<TCComponent>();
   
   }
   
   String dataType[] = {"ItemRevision"};
   String dataRelation[] = {"IMAN_specification"};
   
   @Override
   public Object execute(final ExecutionEvent event) throws ExecutionException {
      ISelection sel = HandlerUtil.getActiveWorkbenchWindow(event).getActivePage().getSelection();
      final StringBuilder objectsSelected = new StringBuilder();
      objectsSelected.append("Here are the objects selected:\n");

      if ((sel != null) && (sel instanceof IStructuredSelection)) {
               IStructuredSelection structSelection = (IStructuredSelection) sel;
               for (Iterator<?> iter = structSelection.iterator(); iter.hasNext();) {
                     AIFComponentContext element =  (AIFComponentContext) iter.next();
                     TCComponent selectedDataset = (TCComponent) element.getComponent();
                     //TCComponent selectedDatasetType = selectedDataset.getTypeComponent();
                     AIFComponentContext[] selectedRevisions;
                     try {
                          selectedRevisions =  selectedDataset.whereReferencedByTypeRelation(dataType, dataRelation);
                          int size = selectedRevisions.length;
                          //objectsSelected.append("Size: " + size + "\n");
                          System.out.println("size" + size + "\n");
                              //objectsSelected.append("Parent Type:  " + Arrays.toString(selectedRevisions) + "\n");
                              if (size == 1) {
                              TCComponent tcDataset = (TCComponent) selectedRevisions[0].getComponent();
                                 revisionList.add(tcDataset);      
                            }
                        else {
                                System.out.println("Terminate\n");
                              continue;
                          }                                                            
                        }
                        catch (TCException e) {
                              // TODO Auto-generated catch block
                              e.printStackTrace();
                        }
                     /*TCComponent parentType =  selectedParent.getTypeComponent();*/
                    
                        
                        datasetList.add(selectedDataset);
              }               
      }
         
      Iterator<?> it = revisionList.iterator();
      while (it.hasNext()){
      objectsSelected.append(it.next()+" ");  
      }
     
      Iterator<?> is = datasetList.iterator();
      while (is.hasNext()){
      objectsSelected.append(is.next()+" ");  
      }
     
     
      Display.getDefault().asyncExec(new Runnable() {
         public void run() {
            MessageDialog.openInformation(HandlerUtil.getActiveShell(event), "ediHandler", objectsSelected.toString());
         }
      });
/*
      IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
      MessageDialog.openInformation(
            window.getShell(),
            "UnprereleaseHandler",
            "Hello, from UnprereleaseHandler");
*/
      return null;
   }
}
0
 
LVL 47

Expert Comment

by:for_yan
Comment Utility
Idf you want each element of your queueList to contain one erevisionList and one datasetList
why wouild not you create a class
which will hold these two lists and provide getter methods whioch will retirive lists from the
instance of thjis class, the popuylate your queueList with nstance of this calass:

class TwoLists {
ArrayList<TCComponent> revisionList ;
ArrayList<TCComponent>datasetLList


TwoLists(ArrayList<TCComponent> revisionList, ArrayList<TCComponent>datasetLList){
this.revisionList = revisionList;
this.datasetList = datasetList;


}

ArrayList<TCComponent> getDatasetList () {
return datasetList();

}

ArrayList<TCComponent> getRevisionList () {
return rervisionList();

}



}

Open in new window


depending on what you do with queueList maybe you'll want to define
method equals() for this class alao

and then you  populate queuyeList with your TwoLists objects

queyueList.add(new TwoLists(revisionList, datasetList))



0
 

Author Comment

by:jkteater
Comment Utility
I am wanting to use the list to store the values from the selection in the current class. Then in a seperate class I will populate a jtable with the values from queyueList..  From the components in the list I will be able to pull other information related to that component in my table.  I don't think this list will be needed a lot, but you may be correct above.  I am just a little confussed.
0
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 

Author Comment

by:jkteater
Comment Utility
There is a relationship between the list.  

The datasetList component is the child of the revisionList component.  So the two values are some what  related and should be together in the queueList.

0
 
LVL 47

Expert Comment

by:for_yan
Comment Utility
I believe you should be able to do all of that with your custom class which will have two lists as instance variables.
I used such things in similar situations and they worked fine. You just may need to add some of the methiods as needed -
say, you may want to have equals() method if you want to use says contains() method, os some cvompareTo() metghod if you want to order them.
0
 
LVL 47

Expert Comment

by:for_yan
Comment Utility
what you mean by "the child"?
Does the information conatined in revisionList inclue the inforamtion within the datasetList ?
If not, then you need to have them both in your class.
0
 

Author Comment

by:jkteater
Comment Utility
So you are suggesting that I create a new class.  Pass in the values of datasetList and ReveisionList.

so instead of adding the data to the list like this
revisionList.add(tcDataset);      

I would be sending the value to the class twoList

twoList(revsionList);

I am just not sure what creating the new class gains for me.  

Please show me how I would replace those spots with the new class you are taking about.  Also if I create the new class, how would I be able to retrieve the values in a seperate class to populate my table.

I am going to go ahead and max the points out -  You are giving a lot of help and deserve the points




for (Iterator<?> iter = structSelection.iterator(); iter.hasNext();) {
	        	 AIFComponentContext element =  (AIFComponentContext) iter.next();
	        	 TCComponent selectedDataset = (TCComponent) element.getComponent();
	        	 //TCComponent selectedDatasetType = selectedDataset.getTypeComponent();
	        	 AIFComponentContext[] selectedRevisions;
	        	 try {
	        		selectedRevisions =  selectedDataset.whereReferencedByTypeRelation(dataType, dataRelation);
	        		int size = selectedRevisions.length;
	        		//objectsSelected.append("Size: " + size + "\n");
	        		System.out.println("size" + size + "\n");
					//objectsSelected.append("Parent Type:  " + Arrays.toString(selectedRevisions) + "\n");
					if (size == 1) {
					TCComponent tcDataset = (TCComponent) selectedRevisions[0].getComponent();
					   revisionList.add(tcDataset); <== here is the place for revisionList	
		          	}
		            else {
		        		System.out.println("Terminate\n");
		        	    continue;
		        	}										
				} 
				catch (TCException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	        	 /*TCComponent parentType =  selectedParent.getTypeComponent();*/
	        	
				
				datasetList.add(selectedDataset); <== Here is the one place for datasetList (
	        }

Open in new window

0
 
LVL 47

Expert Comment

by:for_yan
Comment Utility

I'm not saying "instead"
>so instead of adding the data to the list like this
>revisionList.add(tcDataset);      
you do create bothe lists and then put them into one TwoLists object
using the constructor of the class TwoLists

or you may have the class TwoSets and indeed
have constructor whicvh wil take tcDataSet and tcRevisionSet
 


In general, I was responding to your request - you said yyou have two lists - you want to
have them in one object
>queueList[0] = revisionList[0], datasetList[0]
 - I suggested how you may  do it by replacving two lists with one object
 conatining both lists


why do you want to have two lists in one object - i don't knwo - that's waht you wanted

I can tell you that I do such things sometimes when I have a method from wjhich I want to
get two values - in order to return two valuies (say two objects) - I cannot put them both in one return statement
for such situaions I create the class which wraps together two objects into one
I thouught maybe you have some similar need
This is the method to create one entity out of two - sometimes it is necessary.


If that is not your case, then explaibn why you want to create one list which will contains infornmation from two lists - what is the need for that?











0
 
LVL 47

Expert Comment

by:for_yan
Comment Utility
Pasting big chunks of code at least from my point of view can make it easier for me to help
you only in the case if this code is self-standing, meaning that I may paste it into my IDE
and at least compile and maybe also run it - then compiler and runtime may help
me understanding better your point.  

I cannot use in this way your code as it has many specific classes which I don't have.
So unless you can remove the depnedencies from the code temporarily and post it in this way,
in such situation it would be better if you post small snippets and indicate more
clearly what is yor question related to those snippets.
Otherwise it is very difficult to follow big chunks of code just with my eyes
without haveing IDE that could help me (compiler is certainly much smarter than me in this respect)

0
 

Author Comment

by:jkteater
Comment Utility
Let me try to explain a little about the data structure and why I need to have both in one list.

Object A < has many attributes with it
     |
    \/
ItemRev < has the Attribute TYPE, which other attributes as well such as ID, Name, etc....)
    |
   \/
TYPE <MASTER> - This value is what is displayed in the UI that the User sees and selects.  

So the code I am showing in the above post is getting TYPE (MASTER) (because it is the only thing that can be selected or seen by the user).  I am placing that value in my datasetList.   In the same FOR loop I am traversing the relationship of the TYPE( MASTER ) that is selected and getting the ItemRev component (simular to a parent).  I am placing that value in revisionsList.  

So in datasetList I have the selected TYPE (MASTER) and in revisionList I have the related ItemRev component for the selection.  The reason I have to put them in a list is because there may be more that one TYPE (MASTER) selected by the user.  I have all this working.  But when I need to go to my dialog class and populate a jtable.  

Jtable columns
Item ID   RevID   etc.....

These values come from the revisionList object,  It is almost like a key - value map.  my table will know the  TYPE then I can use the object ItemRev from the list to pull the rest of the values needed.

Let me try to do a simple one.

Screw (Object) (has a attribute or relationship itemRev)
    |
Screw A/1 (ItemRev)(has attributes Item ID, Rev ID, etc...)
    |
Screw (TYPE)(type does not have any attributes - but is the only thing the UI displays to the users)

I select Screw (TYPE) it is placed in datasetList, then I traverse to get the ItemRev Screw A/1 which is placed in revsionList.

datasetList[0] = Screw
revisionList[0] = Screw A/1

I put them in a list, then in my other class when populating my Jtable.  I can put in the TYPE (Screw) but then get data from the ItemRev from Screw A/1

Hope this makes more since
0
 
LVL 47

Expert Comment

by:for_yan
Comment Utility

So let me try to explain what I can uindesrtand from this

So you have Objects each of them cotains an object ItemRev
and tyhis ItemRev has many attributes including  Type - this is probably String?,   ItemId, RevID - say numbers, then some - say strings, maybe some dates, etc.

and you deal with the collections of such objects and you want to put them into JTable wher each
row will correspond to an Object and the columns will be  ItemID, RevID, etc,
proably also TYPE will be the first column - ?

Is this correct ?








0
 

Author Comment

by:jkteater
Comment Utility
yes - that sounds correct
0
 
LVL 47

Expert Comment

by:for_yan
Comment Utility
No, I think that was not quite correct.

the correct thiing is that one Object may contain severeal objects of ItemRev and each of them (which was correct) does have Type, RevID,UtemId, etc.

and user will see the vlaue of Type and he'll select it several times thus populationg your Object with the array/list of ItemRev's - correct

and TYPE is directly related to the rest of the parameters - so if users selected TYPE1 than we know the contents of all fierlds of ItemRev which has this TYPE - correct?

0
 

Author Comment

by:jkteater
Comment Utility
the correct thiing is that one Object may contain severeal objects of ItemRev and each of them (which was correct) does have Type, RevID,UtemId, etc.

Yes

and user will see the vlaue of Type and he'll select it several times thus populationg your Object with the array/list of ItemRev's

Close but user will see the Types, he will only be able to select that Type once, but they can multi select different Types.  They may select Screw,Bolt and Nut.  So that is 3 different Types and each one of them will have a different ItemRev.

and TYPE is directly related to the rest of the parameters - so if users selected TYPE1 than we know the contents of all fierlds of ItemRev which has this TYPE

Yes if they select TYPE1 we know the ItemRev from the traverse code and from ItemRev we can get the rest of the fields
0
 
LVL 47

Accepted Solution

by:
for_yan earned 500 total points
Comment Utility
So if that was correct, then I would make a custom class

ItemRev which will contain all those fields - String TYPE, int Item_ID, int Rev_ID, ...

it will have a constructor

ItemRev(String type, int item_id, int rev_id,....)

where you'll assign all those fields

It will also have getter methods

Srtring getTYPE(){
return TYPE;
}

int getRevID() {
return rev_ID;
}

....


then I'll create HashMap<String, ItemRev>

and put into this HashMap all possible itemRev that you have - yes you 'll have TYPE inside ItemRev and TYPE as a key t HashMap entry - not a probem
I hope you have finite numer of TYPE choices which each user has to select form - so
all of these types will be in this HashMap which will charcaterize your overall colletion of ItemRevs and is indeoendent of any user

Then I'll make a list for each user -
userObjects = new ArrayList<String>;

then when user is seletcing types

I'would be adding TYPE's to this ArrayList

then hwne I need to show contents of uesrList in the JTable


I will iterate through ArrayList - get the next TYPE, retrive the ItemRev object corresponding to that TYPE

and using getRevID(), getItemID(), etyc methods will be able to get all parameters ciorresponding to this type and
populate the row of the JTable with those parameters


 



0
 
LVL 47

Expert Comment

by:for_yan
Comment Utility
Then your reply confirms my assumptuion - so what I typed above should work.
0
 
LVL 47

Expert Comment

by:for_yan
Comment Utility
Framkly when I have such cases if I have not too many fields in say ItemRev (say, less than 5) instead of creating custom class
i may have up to 5 HashMaps - TYPE-RevID, TYPE-ItemID, etc.
That will be probably a little bit less typing than having additional class, though it is not recommended way of course.
but if you have really many fields there in your RevItem then it is better to create custom class representing RevItem and have just one HashMap
keeping all data
0
 

Author Comment

by:jkteater
Comment Utility
Thanks for all your work on this question.   Looking over all this stuff that I have read and your suggestions, I have a simple question that I am going to ask next.  Nothing quite as complicated as this one.  Simple mapping question.
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
jkteater - can you please explain what happened here - i mentioned originally using a Map (as opposed to List instances as for_yan was suggesting)

Slowly but surely for_yan's suggestions transform into using a Map and then you close the question, completely ignoring my comments. Why!?
0
 

Author Comment

by:jkteater
Comment Utility
CEHJ - I am very sorry if you feel that I ignored your suggestions.  You have helped me so many times in the past.  It is never my intention to ignore any ones suggestions.  The problem I run in to is basically, I am very new to java and I am on a very quick time line.  I did not not think I would be able to use a map when I started this question because I thought I had to use 2 list. There was not way I could see it any other way. As the progression went along, I started to understand that If I could build some logic in the selection, I would not have to have 2 list and the map would work.  
Looking back - I should have split the  points accordingly.
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Suggested Solutions

Windows Script Host (WSH) has been part of Windows since Windows NT4. Windows Script Host provides architecture for building dynamic scripts that consist of a core object model, scripting hosts, and scripting engines. The key components of Window…
This article will show, step by step, how to integrate R code into a R Sweave document
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
This video teaches viewers about errors in exception handling.

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

6 Experts available now in Live!

Get 1:1 Help Now