Reputation: 57
private ArrayList<SocialMediaAccount> socialMediaAccounts;
public void addSocialMediaAccount(String userID, String websiteName, String websiteURL, int activityLevel)
{
SocialMediaAccount object = new SocialMediaAccount(userID, websiteName, websiteURL, activityLevel);
socialMediaAccounts.add(object);
}
I have this ArrayList
and I need to search for a particular websiteName and return the userID associated with the object.
Getting confused a lot and would like some help on getting started with this problem.
Thanks!
Upvotes: 1
Views: 160
Reputation: 681
This should work.
//This method will return the userID associated with the given target websiteName.
//Insert it where you need it.
public String search(String targetWebsiteName){
//loop through each account in your list.
For(SocialMediaAccount acc: socialMediaAccounts){
SocialMediaAccount tempObject = acc;
//check for websiteName
if(tempObject.getWebsiteName().equals(targetWebsiteName)) return tempObject.getUserID();
}
return null;
}
//Add these methods to your SocialMediaAccount class
class SocialMediaAccount{
//Getters for object variables
String getWebsiteName(){
return websiteName;
}
String getUserID(){
return userID;
}
}
Upvotes: 1
Reputation: 616
I suppose this method will solve your question. Hope you have getters inside your socialMediaAccount class.
public String getuserID(ArrayList<SocialMediaAccount> socialMediaAccounts,String websiteName){
for(SocialMediaAccount s:socialMediaAccounts){
if( s.getWebsiteName().equalsIgnoreCase( websiteName)){
return s.getUserID;
}
}
return "no user found";
}
Upvotes: 1
Reputation: 4592
If you have a lot of items in your list and you're doing a lot of searches, a HashMap
using the the website name as the key will be much faster.
Upvotes: 1
Reputation: 6265
You can go through the arraylist and check if the websiteName matches the websiteName that is stored in the list like this:
for(int i = 0; i < socialMediaAccounts.size(); i++)
if(socialMediaAccounts.get(i).getWebSiteName().equals(the_website_you_arelooking_for){
return socialMediaAccounts.get(i).getUserId
}
}
Upvotes: 2
Reputation: 1189
I think what you will want
for (SocialMediaAccount socialMediaAccount: socialMediaAccounts) {
if (socialMediaAccount.getwebsiteName() == your_website_search_name) {
return socialMediaAccount.getId();
}
}
return null;
Upvotes: 0