iterate through the objects of a class - java

I have created this class.
public class UserData {
private int user_Id;
private List<String> disease_List=new LinkedList<String>();
/*Constructor*/
public UserData(int u_id, List<String> d_list)
{
this.user_Id=u_id;
this.disease_List=d_list;
}
}
I created around 500 objects by reading data from file.
Now I want to search for values. For example If user enters a disease= allergy.
I want to iterate through all objects and display users that have allergy in disease_list.
I have searched on internet for this but have not found anything useful.

You have to add the userData objects in a collection and iterate them and access it's attributes say disease_list.
For example, if you've added the userData objects in a arrayList, you can iterate in the following way
for(UserData user:UserDataList){
if(user.disease_list.contains("allergy") {
//display the user details
}
}

I might have misunderstood the question.. But basically what you want to do is search for a certain keyword in the disease_List inside every UserData object, right?
So say you have added a String allergy = "allergy"; inside the disease_list.
What you want to do in order to find this you need to iterate through the disease_list instance.
for (int i = 0; i < disease_list.size(); i++) {
if(disease_list.get(i).equals("allergy")){
//Now you know this UserData object contains "allergy". Now you
//can choose to break the iteration and do something with
//the object.
}
}

You can use Lambdas expression (with java 8 or higher) to sort lists.
public class UserData {
private int user_Id;
private ArrayList<String> diseases;
/*Constructor*/
public UserData(int u_id, ArrayList<String> d_list)
{
this.user_Id=u_id;
this.diseases=d_list;
}
public ArrayList filter(String disease) {
return Arrays.stream(diseases).filter(x -> x.equal(disease)).toArray();
}
}

Java doesn't just automatically make a list of every object you create, you need to make the list yourself.
public class UserData {
/* This must exist somewhere */
private static List<UserData> everyone = new LinkedList<UserData>();
private int user_Id;
private List<String> disease_List=new LinkedList<String>();
/*Constructor*/
public UserData(int u_id, List<String> d_list)
{
this.user_Id=u_id;
this.disease_List=d_list;
everyone.append(this);
}
/* Iterator for all the objects */
public static Iterator<UserData> iterator() {
return everyone.iterator();
}
}

if you want to iterate here is one way
for(String disease:disease_list){
if(disease.equalsIgnoreCase("allergy")
log.info("You find out the Result");
}
else you can use contains() method
if(disease_list.contains("allergy")){
log.info("found the disease");
}

Related

How can I store objects from another class in an ArrayList from a different class?

I am quite new to programming. I am creating a project where in class Countries there is data in the form of objects which contain the name of the country and the country's dialing code. There is another class called CountriesList where all the objects from class Country will be stored in an ArrayList. And finally class person where the user will input his country name and phone number and the system will match the country name with the data stored in the array-list and output the dialing code/phone code.
Now the problem is, I can't store the objects from class Countires in the array-list from class CountriesList. Does anyone know how I can store objects from another class in an array list? I tried various ways, but it kept giving errors.
Source code:
public class Countries {
private String countryname;
private int phonecode;
public Countries(String n,int c){
this.countryname=n;
this.phonecode=c;
}
public String getCountryName(){
return this.countryname;
}
public int getPhoneCode(){
return this.phonecode;
}
public static void main(String[] args){
Countries usa = new Countries("USA",1);
Countries india = new Countries("India",91);
Countries antarctica = new Countries("Afg",677);
Countries bangladesh = new Countries("Bangladesh",880);
Countries uk = new Countries("UK",44);
}
}
public class CountriesList {
private Countries list;
public CountriesList(){
ArrayList<Countries> list = new ArrayList<>();
}
public static void main(String[] args){
}
}
Name your class in the singular rather than plural. Each object will represent a single county.
Java conventions for naming variables is camelCase.
More briefly define your country class as a record.
record Country ( String name, int phoneCode ) {}
Just use a List such as ArrayList directly. No need to make a class just to contain a list.
List < Country > countries = new ArrayList<>() ;
countries.add( new Country( "United States , 1 ) ) ;
Use List.of to put all the countries into an unmodifiable list in a single statement.
Search list by the property of name.
String target = "United States" ;
Optional < Country > c =
countries
.stream()
.filter( country -> country.name.equals( target ) )
.findAny()
;
Wrapping your collections (in your case the List) CAN be best-practice, and this is what is then referred to as First Class Collections, but you should only wrap them if you want to add additional behavior (methods) around the collection e.g. some predefined filter behavior or optional appending based on domain checks.
If you are not planning to create or use additional methods others than the ones the collection API already provides, then you don't need the wrapper and you can simply use the List/Set/Queue whatever that you have.
Btw; you should have written your code like below in order to achieve what you wanted to do, passing the collection via the constructor of the wrapper.
public class CountyList {
private static final Predicate<Country> disallowPhoneCode999Predicate = (c) -> c.getPhoneCode() != 999;
private final List<Country> list;
public CountyList(List<Country> countyList){
this.list = countyList;
}
// delegate methods
public Country get(int index) {
return list.get(index);
}
// add additional methods (very silly example)
public void addConditionally(Country country) {
if (disallowPhoneCode999Predicate.test(country)) {
list.add(country);
}
}
// or return the wrapped collection (not the best approach design-wise but possible)
public List<Country> getWrappedCollection() {
return list;
}
}
public class Application {
public static void main(String[] args){
List<Country> countries = List.of(
new Country("USA",1),
new Country("India",91));
CountyList countriesList = new CountyList(countries);
countriesList.addConditionally(new Country("Bangladesh", 882));
countriesList.add(new Country("Afg", 677));
}
}

Choosing between `Collection <MyObject>` inside vs outside of `MyObject` class [Java]

What is the best way to store a Collection<MyItem> ? This collection is effectively static for current user. Each user can only see their collection. MyItem item implements IItem:
public interface IItem {
public Integer getItemID();
public void setItemID(Integer id);
public String getTitle();
public void setTitle(String title);
/*more getters and setters*/
public IItem parseServerResponse(String response);
public int postItem(); //posts this IItem to server, return ok ->200, unauth->401, etc
public IItem findItem(String[] filters);
/*more advanced methods*/
}
I can store Collection<MyItem> elsewhere, but then I can't access private MyItem methods from CurrentMyItems:
public class CurrentMyItems{
private final List<IItem> allItemsList;
public CurrentMyItems(String allItemsServerResponseString){
JSONArray rawItems = parseResponse(allItemsServerResponseString);
int arrSize = rawItems.length()+estimateQuantityOfNewItems();
List<IItem> allItemsList = new ArrayList<>(arrSize);
for (int i = 0; i < Items.length(); i++) {
allItems.add(i, parseItem(Items.get(i)));
}
}
/*methods*/
}
Or inside of the MyItem class (see commented out options):
public class MyItem implements IItem {
/*
private final static List<IItem> allItemsStaticList = new ArrayList<>();
private final static Map<Integer, IItem> allItemsStaticMap = new HashMap<>();
private final List<IItem> allItemsList; //
private final static Map<Integer, IItem> allItemsMap;
*/
/*implemented methods*/
}
allItemsStaticList - stores a static list of all Items. Seems memory efficient, but what if I need to store separate collections of MyItems in future? This is highly unlikely, but still...
allItemsList - Same class has two distinct functions. It is either
storing a single Item, in which case allItemsList/Map = null;
or
allItemsList = new ArrayList<>();, while other fields are empty.
This seems OK, but it breaks the Least Surprise Principle.
Which approach to store a MyItemCollection is more natural?
Also, should I store Items as a Map or a List given that MyItem myItem = getMyItemByID(int id); is the main way to access MyItem?
Update
We can implement an Item class so that an instance can either hold a collection of Item instances or the modeled data, but not both.
public class Item {
private final Map<Integer, Item> itemsMap;
private final IntegerProperty itemID; // private final String[] names;
public Item(){
itemsMap = new HashMap<>();
itemID = null; //names = null;
}
private Item(Integer id) {
itemsMap= null;
itemID = new SimpleIntegerProperty(id); //names = new String[1];
}
public Item makeGenericItem(){
return itemsMap == null ? null : new Item(itemsMap.size());
}
// other methods, including getters and setters
}
But at what cost?.. This class violates single responsibility principle.
Conclusion - in most cases a Collection of Item instances should be stored outside of Item class.
In OOP the data elements of an object are also known as attributes of the object. So, you should ask yourself whether a collection of items is an attribute of an item or not.
For example, when you assume your items are students. Would you say that a list of students is an attribute of a student? -- Probably not, as a list of students is not part of a student. Instead a student is part of a list of students.
Since a list of students is not an attribute of students in real life, I would not model it differently in code just to make it technically more elegant.
The design of your classes should be driven by the structure of the domain that your are working in. When you need to decide where to put an attribute do not ask "does it make sense to put it here because of the features my programming language offers?" but ask "where does this attribute belongs to in my domain?".

How do I do this? Add a method to add one ingredient at a time (use a single String variable as the parameter. Do not pass it an array)

Disclaimer: I am new to programming so my code might be noobish. Anyway, I'm working on a reference data type class and one of the instructions says;
Add a method to add one ingredient(I'm assuming to the ingredients array) at a time (use a single String variable as the parameter. Do not pass it an array).
the way I have it right now there is an array, but I cant quite figure out how to create this method with just a single string variable. Again I'm still very new to this.
P.S. the assignment is to create compliable reference data type class not a running program(yet). There more to the code but this is the part I thought was most relevant.
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
//default constructor
public class Recipe{
private String recipeName="";
private String [] ingredients = new String[20];
private String [] instructions = new String[20];
public Recipe(){
for(int i=0;i<ingredients.length;i++){
recipeName="";
ingredients[i]="";
instructions[i]="";
}
}
//getset recipeName
public String getName(){
return recipeName;
}
public void setName(String inName){
recipeName = inName;
}
//getset ingredients
public String[] getIngredients(){
return ingredients;
}
public void setIngredients(String[] inIngredients){
ingredients = inIngredients;
}
If you would like to add ingredients one by one to your recipe and get the list of ingredients, the following should help.
private List<String> ingredients = new ArrayList<String>();
...
public void setIngredients(String ingredient){
ingredients.add(ingredient);
}
public List<String> getIngredients(){
return ingredients;
}
Change your ingredients array to ArrayList
private List<String> ingredients = new ArrayList<String>();
Then create methods to add one ingredient to it:
public boolean addIngredient(String ingredient){
return ingredients.add(ingredient);
}
Hope you can use arrayList which are better, but if you must use array:
public void addIngredient(String ingredient){
for(int i=0; i<ingredients.length;i++){
if("".equals(ingredients[i])}{
ingredients[i]=ingredient;
return; //no need to add more than once
}
}
}

Replace an object in a List<Object> when Object is a List? Java

Hello again stackoverflow,
I have a question concerning List of Objects.
I have tried out writing some things, but can't find it though.
How do I find an Object in a list of objects, when these objects are lists of its own?
this is what i have so far:
Recipe is a List of: {modification[], ingredients[], recipeBookName, recipeName}
public void removeFromBook(Recipe recipeName) {
recipes = getRecipes();
emptyRecipe = getEmptyPage(recipeBookName);
Now, I want to replace a Recipe which has a recipeName, by the emptyRecipe.
I think it will be something like:
for(r in recipes) {
if(r.recipeName == recipeName) {
list.replace(Recipe, emptyRecipe)
} else {
}
}
any ideas? :)
here's my constructor for the Recipe class:
public String[] modifications;
public String[] ingredients;
public String recipeName;
public String partOfRecipeBook;
public Recipe(String recipeName, String[] modifications, String[] ingredients, String recipeBookName){
setRecipeModifications(modifications);
setRecipeIngredients(ingredients);
setRecipeName(recipeName);
setRecipeBookName(recipeBookName);
}
Using a List with Objects in it (of which some are arrays) is not the best way it would be better to define a new object Recipe and use that.
public class Recipe {
private List<Ingredient> ingredients;
private List<Modification> modifications;
private String bookName;
private String book;
}
Then replacing in ingredients is a lot simpler. e.g. give recipe a function like
public void replaceIngredent(Ingredient oldIngredient, Ingredient newIngredient) {
int index = ingredients.indexOf(oldIngredient);
if (index != -1) {
ingredients.remove(index);
ingredients.add(index, newIngredient);
}
}
Your approach looks fine, except that you should compare strings with equals:
if(r.recipeName.equals(recipeName)) {
Now an even easier way would be to store your recipes in a Map:
Map<String, Recipe> recipes = new HashMap<String, Recipe>();
recipes.put("Pizza with Lobster", new Recipe());
when you want to replace a recipe:
recipes.put("Pizza with Lobster", emptyRecipe);
and the old recipe has been replaced.
private List<TimeModel> timeModels = new ArrayList<TimeModel>();
then you simply put
timeModels.set(0, new TimeModel("6:00 PM"));
and after that set yourAdapter.notifyDataSetChanged();

How to print the output of an accessor of every instance of a class?

How would you go about creating a class like this:
public class tmUser {
private String Username;
private int wHours;
static int numUsers;
public tmUser(){
Username = "";
wHours = 0;
}
public tmUser(String U, int H){
Username = U;
wHours = H;
}
public void setUsername(String U){
Username = U;
}
public void setwHours(int H){
wHours = H;
}
public String getUsername(){
return Username;
}
public int getwHours(){
return wHours;
}
public static void initnumUsers(){
numUsers = 0;
}
public static int getnumUsers(){
return numUsers;
}
}
and then printing all of tmUser instances Username variable? in maybe a for each loop? I'm hoping for something like:
for each(tmUser){
System.out.println(Username);
}
This is for a menu in a program which displays all created users usernames.
You almost had it:
List<TmUser> tmUsers = ...
for(TmUser user : tmUsers) {
System.out.println(user.getUsername());
}
You would also want to capitalize tmUser into TmUser.
When you create a tmUser add it to a collection like
List<TmUser> tmUsers = new ArrayList<TmUser>();
TmUser tmUser = new TmUser(username, hoursWorked);
tmUser.add(tmUser);
// later
for(TmUser tmUser: tumUsers)
System.out.println(tmUser.getUsername());
You need to store all of tmUser instances somewhere first. You could do it this way:
public class tmUser {
...
public static List<tmUser> USERS = new ArrayList<tmUser>();
public tmUser() {
...
USERS.add( this );
}
and then printing:
for (tmUser user : tmUser.USERS) {
System.out.println(user.getUsername());
}
The 3 current answers are basically the same. Just wanted to add that if the class defined a toString() that returned the user name, it would not be necessary to add the .getUsername() method call, since System.out.println(Object) will automatically call the toString() method.
Whether this could work for your use case is debatable. The toString() method would normally provide more data on the object.
As the answers already posted indicate, this would involve maintaining some sort of data structure that holds references to all instances of tmUser (e.g. a List<tmUser>).
This would mean that a reference to each and every instance ever created will always be held there, they will never be garbage collected. You could explicitly remove them when you decide an instance is no longer needed, but then you would have to keep track of the life cycle of all instances, and basically end up doing memory management yourself.

Categories

Resources