Convert String to object in java - java

I have a HashSet in where I need to store the available ingredients.
HashSet<Ingredient> availableIngreds = new HashSet<>();
The available ingredients are read from a file.
Scanner file = new Scanner(new File(fileName));
while (file.hasNext()) {
availableIngreds.add(file.next()); //Non working code
}
System.out.println("*** Available ingredients ***");
for (Ingredient i : availableIngreds) {
System.out.println(i);
}
My problem is that the file contains the ingredients as strings (flour, sugar, milk etc).
My HashSet needs to store the ingredients as object of the class Ingredient.
How can I convert String to Ingredient so the above line of code works?
Thank you for your help.
* edit *
class Ingredient:
public class Ingredient {
private String iName;
public Ingredient(String aName) {
iName = aName;
}
public String getName() {
return iName;
}
public String toString() {
return iName;
}
public boolean equals(Object rhs) {
return iName.equals(((Ingredient)rhs).iName);
}
public int hashCode() {
return iName.hashCode();
}
}

You already have a constructor for Ingredient that accepts a String. Just use it when adding values to your HashSet:
while (file.hasNext()) {
availableIngreds.add(new Ingredient(file.next()));
}

Since file.next() returns a String, and you need to create in Ingredient object from it, overload the constructors with one that take a String as a parameter (I'm assuming that your Ingredient class has a String field in which you store the actual ingredient name), create the Ingredient object you want with it and then store it in your Hashmap.

Related

How to randomly list values of an enum located in a different package in Java?

If I have two classes (Character and Person) that are located in the same package and one class(Audit) that is located in a different package from Character and Person, how can I randomly list values in the enum in Character and Person?
In the Character class,
public abstract class Character{
private int age;
private BodyType bodyType;
public enum BodyType
{
AVERAGE,
ATHELETIC,
UNSPECIFIED;
}
public Character(int age, BodyType bodyType){
this.age = age;
this.bodyType = bodyType;
}
public int getAge(){
return this.age;
}
public BodyType getBodyType(){
return this.bodyType;
}
public void setAge(int age){
this.age = age;
}
public void setBodyType(BodyType bodyType){
this.bodyType = bodyType;
}
}
In the Person class, which extends Character
public class Person extends Character{
private AgeCategory ageCategory;
public enum AgeCategory
{
CHILD,
ADULT;
}
public Person(int age, BodyType bodyType){
super(age, bodyType);
}
public AgeCategory getAgeCategory()
{
if (getAge() >=0 && getAge() <=16){
return AgeCategory.CHILD;
}
if (getAge() >=17){
return AgeCategory.ADULT;
}
return ageCategory;
}
}
In the Audit class located in different package, I have to return strings. I’ve tried the following code, but this just results in the enumeration in order . What I wanted to do here is that I want to get all enum values listed but in random order.
public class Audit{
public String toString()
{
String strings = “random enumeration\n”;
for (BodyType bodyType : EnumSet.allOf(BodyType.class)) {
strings += bodyType.name().toLowerCase() + ":";
strings += "\n";
}
for (AgeCategory ageCategory : EnumSet.allOf(AgeCategory.class) ) {
strings += ageCategory.name().toLowerCase() + ":";
strings += "\n";
}
return strings;
}
}
That's the behaviour of EnumSet.
The iterator returned by the iterator method traverses the elements in their natural order (the order in which the enum constants are declared).
Refer this
Or
Try
List<BodyType> randomType = Arrays.asList(BodyType.values());
Collections.shuffle(randomType);
for (BodyType type : randomType) {
System.out.println(type);
}
To achieve that[in your comment - mix of all enum types]:
Your ENUMs should share common type and use shuffle.
Iterate ENUM of BodyType and store in list
Iterate ENUM of AgeType and store in the same List
Shuffle
Print
it seems you are already very close to the desired solution, especially with the help of the above answer.
Below is a complete solution for what you seem to be after. Basically it iterates over both enums, stores the lowercase name of each value in a list, shuffles the list, then builds a string with its contents:
public class Audit {
public String toString()
{
List<String> names = new ArrayList<>();
for (BodyType bodyType : BodyType.values())
{
names.add(bodyType.name().toLowerCase());
}
for (AgeCategory ageCategory : AgeCategory.values())
{
names.add(ageCategory.name().toLowerCase());
}
Collections.shuffle(names);
StringBuilder sb = new StringBuilder("random enumeration\n");
for (String name : names) {
sb.append(name).append(":\n");
}
return sb.toString();
}
}
Please note that I've changed the way you generate the string, using StringBuilder is significantly more efficient.
Furthermore I really don't understand why you would need what you are asking for, but I'll assume you have your reasons.

Object to string delimited format

I have set of objects of different types.
Ex : Employee emp, adress adr
These two classes have list of properties
public class Employee{
private Stringname;
private int age;
}
public class Adress {
private String HouseNo;
private string Street;
private string pin;
}
Each attribute is assigned with some 2 character value
Name (NA), age (AG), HouseNo(HN),Street(ST), pin(PN)
I need to construct a string with these data and delimit with a %
Output:
NA%Vidhya%AG%30%HN%80%ST%1st cross%PN%100100
Each class knows it own data best so I would let each class be responsible for generating the string. As I understand it the two char codes for each field are unique for each class and member and only used when generating the string so only the class would need them.
interface AttributeDescription {
String generateDescription();
}
public class Employee implements AttributeDescription {
//members...
public String generateDescription() {
return String.format(“NA%%%s%%AG%%%d”, name, age)
}
Then simply call this method for all objects implementing the interface.
AttributeDescription object = ...
String attr = object.generateDescription();
I don't think it can be generalized more than this given the requirements.
Update
It might be better to have a builder class for building the string to get a more unified behavior between classes. Here is an example
public class AttributeBuilder {
private builder = new StringBuilder();
public String getAttribute() {
return builder.toString();
}
public void add(String code, String value) {
if (value == null) {
return;
}
builder.append(code);
builder.append(‘%’);
builder.append(value);
builder.append(‘%’);
}
}
And then you would also have to implement add(...) methods for other data types in a similar fashion. The builder could then be used like
public String generateDescription() {
AttributeBuilder builder = new AttributeBuilder();
builder.add(“NA”, name);
builder.add(“AG”, age);
return builder.getAttribute();
}

Hashmap using which key and value to search name and phonenumber

I have requirement to put "Name" and "phonenumber" in map.
I dont understand which thing I put as key and value in hashmap.
my requirement is we can and name with phone number and search with name.
like Name:"sanjay" phoneNumber:"111";
Name:"Krish" phoneNumber:"222";
later search it by name if I search 'sanjay' it provide me sanjay's phonenumber.
and, there is more then one user with same name and one user may have more then one phonenumber.
Thanks.
If you have a Person class, make a map like: Map<Person, Collection<String>>.
Then you can find phone numbers by doing map.get(somePerson), which returns null if the person doesn't exist.
You could also consider making a PhoneNumber class, which contains the string value of a validated phone number: Map<Person, Collection<PhoneNumber>>.
Use a class wrapper:
public class Person {
private List<String> phoneNumbers;
private String fullName;
//getters, setters, constructors for field values
#Override
public boolean equals(Object o) {
if (!(o instanceof Person) {
return false;
}
Person p = (Person) o;
return this.fullName.equals(p.fullName); //and other qualifying things
}
#Override
public int hashcode() {
//account for fields that you use in #equals(Object)
}
}
Then you can index based on whatever you want:
/* Full name => People */
Map<String, List<Person>> people = new HashMap<>();
/* Number => Person */
Map<String, Person> people = new HashMap<>();
Keep in mind, if you only compare the name in equals(Object), you're back to square one. Add more things to compare to be consistent with the uniqueness.
Hash maps great power is the ability to find the values in O(1) efficiency.
For this to work, the key must be the object you search by.
For example, if you want to search by name than your key should be the name.
And since a person can have several phone numbers, the value should be a List of phone numbers.
if you want to find the person name according to the phone number you should handle this the other way around - the key would be the phone number and the value would be the person name.
Perhaps you want both...
There are good answers above, may be this will also helps
Here Student made as key by overriding hashCode() and equals() method.
public class Student {
public String studentId;
public String studentName;
public Student(String studentId, String studentName) {
this.studentId=studentId;
this.studentName =studentName;
}
#Override
public int hashCode() {
return 1234;
}
#Override
public boolean equals(Object o) {
if (o instanceof Student) {
Student student=(Student)o;
if (this.studentId.equalsIgnoreCase(student.studentId)) {
return true;
} else {
return false;
}
} else {
return false;
}
}
}
Phone Number class :
public class PhoneNumber {
public String phoneNumber;
public PhoneNumber(String phoneNumber) {
this.phoneNumber =phoneNumber;
}
}
Person Class :
import java.util.HashMap;
import java.util.Set;
import java.util.List;
import com.google.common.collect.Lists;
public class Person {
public static void main(String[] args) {
Student e1=new Student("e001","studentOne");
Student e2=new Student("e002","studentTwo");
PhoneNumber d1 = new PhoneNumber("9999999998");
PhoneNumber d2 = new PhoneNumber("9999999999");
List listOfPhoneNumbersOfStudentOne = Lists.newArrayList(d1,d2);
PhoneNumber d3 = new PhoneNumber("9999999997");
PhoneNumber d4 = new PhoneNumber("9999999996");
List listOfPhoneNumbersOfStudentTwo = Lists.newArrayList(d3,d4);
/* Here Student made as key by overriding hashCode() and equals() method.*/
HashMap<Student, List<PhoneNumber>> map=new HashMap<Student, List<PhoneNumber>>();
map.put(e1, listOfPhoneNumbersOfStudentOne);
map.put(e2, listOfPhoneNumbersOfStudentTwo);
Set<Student> key=map.keySet();
for (Student student : key) {
System.out.println(student.studentId+" "+student.studentName +" ");
}
}
}
public class Assignment4 {
HashMap map = new HashMap<>();
public void addContact(String name, Integer number) {
map.put(name, number);
}
public void getphoneNumber(String name) {
if (map.containsKey(name)) {
Integer a = map.get(name);
System.out.println("Contact of " +name+" is " + a);
}
}
public static void main(String[] args) {
Assignment4 a4 = new Assignment4();
a4.addContact("vishal", 10345);
a4.addContact("sachin", 30456);
a4.addContact("sai", 30458);
Scanner s=new Scanner(System.in);
System.out.println("Enter name to get contact details");
a4.getphoneNumber(s.next());
s.close();
}
}

How to get a specific element from an arraylist that has string and int values from another class

here is my problem.
I have a class A that has a string of names and int of numbers which is placed into an ArrayList of another class.
Task:- what i need to do is get the first name from index(0) from the arraylist and return it as a string.
public class A
{
private String name;
private int num;
public A(String aName, int bNum)
{
name = aName;
num = bNum;
public String getName()
{return name; }
public int getNum()
{return num;}
}
}
//class b inserts elements of class a into arraylist
public class b
{
private ArrayList<A> myList;
}
public b()
myList = new ArrayList<A>;
public void addAll(A all)
{ myList.add(all);}
//get method required for issue above.
Check if the the your list has any item present or no. If present, retrieve the first element and get the name for it to return otherwise return null or empty string as desired.
public String getFirstElementName(){
String name = null;//or ""
if(myList.size() >0){
name = myList.get(0).getName);
}
return name;
}
EDIT:
public A getFirstElement(){
A a = null;//or ""
if(myList.size() >0){
a= myList.get(0);
}
return a;
}
Where you are calling this method, you may write as:
A a = getFirstElement();
String name = a.getName();
int number= a.getNum();
Hope this helps.
List.get(int index) returns the element at position index.
May be what you are looking for is
A firstA = myList.get(0);
String name = firstA.getName();
Also, instead of declaring your list as
private ArrayList<A> myList;
you should declare it as
private List<A> myList;
Code against the interface wherever possible.
You need to override equals() and hashcode() in class A based on object equality requirements.
When you want to do lookup create object for A and set values and do lookup with this object.
Example:
A tempObj = new A("name", 5);
In Class B
myList.get(tempObj);

ArrayList - How to modify a member of an object?

I have a number of Customer objects stored in an ArrayList. My Customer class has 2 data members: Name and Email. Now I want to modify just the Email for Customer "Doe".
Now if "Doe" is located at index 3 in the list, I know I can write this line:
myList.set( 3, new Customer( "Doe", "j.doe#supermail.com" ) );
But that means creating a new object. If I have a very big list, I suppose the process would be very slow. Is there any other way to directly access the data member of an Object stored in an ArrayList, maybe by using another kind of Collection than ArrayList?
You can do this:
myList.get(3).setEmail("new email");
Fixed. I was wrong: this only applies on element reassignment. I thought that the returned object wasn't referencing the new one.
It can be done.
Q: Why?
A: The get() method returns an object referencing the original one.
So, if you write myArrayList.get(15).itsVariable = 7or myArrayList.get(15).myMethod("My Value"),you are actually assigning a value / using a method from the object referenced by the returned one (this means, the change is applied to the original object)
The only thing you can't do is myArrayList.get(15) = myNewElement. To do this you have to use list.set() method.
You can iterate through arraylist to identify the index and eventually the object which you need to modify. You can use for-each for the same as below:
for(Customer customer : myList) {
if(customer!=null && "Doe".equals(customer.getName())) {
customer.setEmail("abc#xyz.com");
break;
}
}
Here customer is a reference to the object present in Arraylist, If you change any property of this customer reference, these changes will reflect in your object stored in Arraylist.
Assuming Customer has a setter for email - myList.get(3).setEmail("j.doe#supermail.com")
I wrote you 2 classes to show you how it's done; Main and Customer. If you run the Main class you see what's going on:
import java.util.*;
public class Customer {
private String name;
private String email;
public Customer(String name, String email) {
this.name = name;
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Override
public String toString() {
return name + " | " + email;
}
public static String toString(Collection<Customer> customers) {
String s = "";
for(Customer customer : customers) {
s += customer + "\n";
}
return s;
}
}
import java.util.*;
public class Main {
public static void main(String[] args) {
List<Customer> customers = new ArrayList<>();
customers.add(new Customer("Bert", "bert#gmail.com"));
customers.add(new Customer("Ernie", "ernie#gmail.com"));
System.out.println("customers before email change - start");
System.out.println(Customer.toString(customers));
System.out.println("end");
customers.get(1).setEmail("new.email#gmail.com");
System.out.println("customers after email change - start");
System.out.println(Customer.toString(customers));
System.out.println("end");
}
}
to get this running, make 2 classes, Main and Customer and copy paste the contents from both classes to the correct class; then run the Main class.
Use myList.get(3) to get access to the current object and modify it, assuming instances of Customer have a way to be modified.
You can just do a get on the collection then just modify the attributes of the customer you just did a 'get' on. There is no need to modify the collection nor is there a need to create a new customer:
int currentCustomer = 3;
// get the customer at 3
Customer c = list.get(currentCustomer);
// change his email
c.setEmail("somethingelse#example.com");
Well u have used Pojo Entity so u can do this.
u need to get object of that and have to set data.
myList.get(3).setEmail("email");
that way u can do that. or u can set other param too.
If you need fast lookup (basically constant time) of a object stored in your collection you should use Map instead of List.
If you need fast iteration of the objects you should use List.
So in your case...
Map<String,Customer> customers = new HashMap<String,Customer>();
//somewhere in the code you fill up the Map, assuming customer names are unique
customers.put(customer.getName(), customer)
// at some later point you retrieve it like this;
// this is fast, given a good hash
// been calculated for the "keys" in your map, in this case the keys are unique
// String objects so the default hash algorithm should be fine
Customer theCustomerYouLookFor = customers.get("Doe");
// modify it
theCustomerYouLookFor.setEmail("newEmail#stackoverflow.com")
Without function here it is...it works fine with listArrays filled with Objects
example
`
al.add(new Student(101,"Jack",23,'C'));//adding Student class object
al.add(new Student(102,"Evan",21,'A'));
al.add(new Student(103,"Berton",25,'B'));
al.add(0, new Student(104,"Brian",20,'D'));
al.add(0, new Student(105,"Lance",24,'D'));
for(int i = 101; i< 101+al.size(); i++) {
al.get(i-101).rollno = i;//rollno is 101, 102 , 103, ....
}
Any method you use, there will always be a loop like in removeAll() and set().
So, I solved my problem like this:
for (int i = 0; i < myList.size(); i++) {
if (myList.get(i).getName().equals(varName)) {
myList.get(i).setEmail(varEmail);
break;
}
}
Where varName = "Doe" and varEmail = "j.doe#supermail.com".
I hope this help you.
Try this.This works while traversing the code and modifying the fields at once of all the elements of Arraylist.
public Employee(String name,String email){
this.name=name;
this.email=email;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setEmail(String email) {
this.email = email;
}
public String getEmail() {
return email;
}
for(int i=0;i++){
List.get(i).setName("Anonymous");
List.get(i).setEmail("xyz#abc.com");
}

Categories