Use a Object by String? - java

Is it possible to use a Object if i only got the String? I have an Object 'John' from the Class 'Student'. In the Class 'Student' is a ArrayList 'friends'. I want to access the Object 'John' by using a String (the name of the object). (Line 2 in the example)
public void addFriend(Student student, String friend) throws IOException{
student.friends.add(friend);
System.out.println("Friend: " + friend + " added to List of " + student);
}
I hope you understand what i mean (i am sorry for my terrible english :/ )

You can use map for this problem.
Map<String, Student> friends = new HashMap<String, Student>();
friends.put("John", objectOfJohn);
Student target = friends.get("John");

If I understand correctly, you want to print out name of a student using the variable student. If this is the case, you may want to override the toString() method inside Student class which returns name of that student. For example:
public class Student {
private String firstName;
private String lastName;
// ... Other methods
// here is the toString
#Override
public String toString() {
return firstName + " " + lastName;
}
}
Then you can do something like this to print out the student name:
System.out.println("Friend: " + friend + " added to List of " + student.toString());

You have a Student Class and you have created in some point some objects of this class.
Student john = new Student();
Student mike= new Student();
Student mary = new Student();
and you have all these objects stored in an Arraylist allStudents
ArrayList<Student > allStudents= new ArrayList<>();
allStudents.add(john);
allStudents.add(mike);
allStudents.add(mary);
So, if you want to find john from this list you may do:
Option A
If the name for your case is unique and exists also as an attribute in your object, you can iterate the Arraylist and find it:
Student getStudentByName = new Student();
for(Student student : allStudents){
if(student.getName().equals("john")){ //If name is unique
getStudentByName = student;
}
}
Option B
Add all objects in HashMap
Map<String, Student> allStudents= new HashMap<>();
allStudents.put("john", john);
allStudents.put("mike", mike);
allStudents.put("mary", mary);
And then get your desired object by:
Student target = friends.get("john");
Be mind that if you add again :
allStudents.put("john", newStudentObject);
the HashMap will keep the last entry.

Related

how to find an item in a SortedSet in Java

I have a Sorted Set in Java with an object with 2 strings, Name and Age. Name is unique.
Now I have the Name and I want to get the age based on the name.
I have my object:
SortedSet<Person> people;
That has 3 people inside: "John / 35", "James / 21" and "Maria /21"
Based on this, I want to check James age.
How can I do it? The only idea I have is just doing a for, but I guess it should be something easier.
I see two solutions there:
If there really are just this two properties, you could simply convert that to a map, where the name is the key and the age is the value, ( Map<String, Integer> ageMap). Then you can quickly get the age by using ageMap.get("James");.
Edit: To convert you can do this:
Map<String, Integer> ageMap = new HashMap<>();
for (Person p : people) {
ageMap.put(p.getName(), p.getAge());
}
int jamesAges = ageMap.get("James");
If you stay with the Set and the Person class, I would recommend using the streams:
Optional findFirst = set.stream().filter(e -> e.getName().equals("James")).findFirst();
if (findFirst.isPresent()) {
int age = findFirst.get().getAge();
}
Internally, this will probably still use some kind of for, but the real implementation might be a bit more optimized.
I would not use a set for this since you cannot easily retrieve values from a set. I would go with a map. You can populate the map anyway you like.
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
#Override
public String toString() {
return "[" + name + ", " + age +"]";
}
}
Map<String, Person> people = new HashMap<>(Map.of("john", new Person("John",35),
"james", new Person("James", 21), "maria", new Person("Maria", 21)));
String name = "James";
Person person = people.get(name.toLowerCase());
System.out.println(person != null
? name + "'s age is "+ person.getAge()
: name + " not found");
prints
James's age is 21

how to override this to get structured manner

i am creating student management simple java project using Maps collection where id is my key and the name,marks and mobile no. are values for the map. So how to print it in structured manner.
HashMap<Integer, LinkedHashSet<StudentCinstructor>> st = new HashMap<>();
LinkedHashSet<StudentCinstructor> st2 = new LinkedHashSet<>();
Scanner sc = new Scanner(System.in);
public void add() {
System.out.println("enter the name of the student");
String name = sc.nextLine();
System.out.println("enter the marks of the student");
double marks = sc.nextDouble();
System.out.println("enter the mobile number of the student");
long mobile_no = sc.nextLong();
st2.add(new StudentCinstructor(name, marks, mobile_no));
System.out.println("enter the unique id of the student");
int id = sc.nextInt();
st.put(id, st2);
with the custom class when i am trying to print it in main method its giving me an address with hashcode.
"HashmapDemo.MethodsForManagement#3d4eac69"
Two remarks :
1- When you try to print the object StudentCinstructor, if there is no dedicated toString() method, you will not get a well structured output. Therefore, what you need to do is write a toString() method for your class and then you can print to console.
Example :
public static String toString() {
return "Customize here + Put this method inside your class";
}
2- I don't see why you are using LinkedHashSet to store the StudentCinstructor objects and then storing this HashSet inside a map rather than creating the StudentCinstructor object and storing it in the Map directly if all students have a unique id.
Such as :
HashMap<Integer, StudentCinstructor> st = new HashMap<>();
Looking at your printed output "HashmapDemo.MethodsForManagement#3d4eac69", it seems you are printing an object of class HashmapDemo.MethodsForManagement. If you want to print an object of StudentCinstructor, you need to pass that object to the print method like System.out.println(student);.
And you need to override the toString() method in StudentCinstructor class. (i.e. put below code in StudentCinstructor class.)
(name, marks and mobile_no in below code are the fields in StudentCinstructor class.)
#Override
public String toString()
{
return "Name=" + name + ", Marks=" + marks + ", Mobile number=" + mobile_no;
}

Iterator is adding the wrong address

In my program I've added an ArrayList of another class type but when I iterate the list I get a wrong address.
For example my code is
ArrayList<Student> stdntList = new ArrayList<Student>();
stdntList.add(new Student("Candace","633501"));
stdntList.add(new Student("Curtis ","634572"));
stdntList.add(new Student("Amber","623343"));
System.out.println(stdntList);
Iterator itr = stdntList.iterator();
while(itr.hasNext())
{
System.out.println("Student: " + itr.next());
}
and my output is
Student Name: Candace Student ID633501
Student Name: Curtis Student ID634572
Student Name: Amber Student ID623343
[Student#659e0bfd, Student#2a139a55, Student#15db9742]
Student: Student#659e0bfd
Student: Student#2a139a55
Student: Student#15db9742
In order to take the address, you should maybe print something like this System.out.println("Student: " + itr.next().getAddress());
As it is now, it prints everything it is on .toString() method. You have to override this method in order to print the address by calling only the reference to the class.

Inputting strings into arrayLists?

Suppose that I have a code empList and it is an ArrayList. I have 3 Strings, name, boss, and dob holding the data for some employee. I want to write code that creates an Employee from my Strings and then adds it to the empList. I can use the add method of ArrayList to add my employee after I have constructed it, but I'm not too sure how.
This is my Employee class I have written so far:
ArrayList<String> empList = new ArrayList<String>();
class Employee{
Employee(String dob, String name, String boss) //(constructor)
//dob should be mm/dd/yyyy, and boss of length 0 indicates no boss.
int getAge()
String getName()
String getBoss() //returns length 0 string if none
String getDob()
You should change the List declaration to List<Emloyee>:
List<Emloyee> empList = new ArrayList<Emloyee>();
(read more about generics in Java: http://docs.oracle.com/javase/tutorial/java/generics/)
Then you can create a new Employee instance and add it to the list:
Employee employee = new Employee("dob", "John Smith", "His Boss");
empList.add(employee);
By the way: consider changing the type of boss from String to Employee (depending on you use case/meaning).
You might be able to do it in your constructor using
empList.add(this);
However, you'd have to change the type of your ArrayList to Employee, or if you wanted to keep it as a String, then you'd have to create a String in your constructor, and do
String str = "Your string here";
empList.add(str);
I'm also pretty sure that you can't have your ArrayList outside of your class. Java doesn't let you have things outside of classes.
You can add strings to the ArrayList by it's add() method.
You already have the getXXX() methods in your employee class, so you can simply do something along the lines of
String str = "Name: " + emp.getName() + ", Boss: " + emp.getBoss() + ", DoB: " + emp.getDoB();
empList.add(str);
What you probably want is an ArrayList of Employees (ArrayList<Employee>), which would be added in a similar manner, without adding everything to a string.

ClassCastException while using GROUP BY clause in JPA

I am working with JPA. while doing GROUP BY clause example it's throwing ClassCastException.
Below Is My code:
public class StudentGrouping
{
public static void main(String[] args)
{
EntityManager entityManager = EntityManagerUtil.getEmf()
.createEntityManager();
try {
EntityTransaction entr = entityManager.getTransaction();
entr.begin();
Query query = entityManager
.createQuery("SELECT student.studentName, SUM(student.studentAge) FROM Student student GROUP BY student.studentName");
List<?> list = query.getResultList();
Iterator<?> iterator = list.iterator();
while (iterator.hasNext())
{
System.out.println("entered into loop");
Student student = (Student) iterator.next();
System.out.print("Student Name:"+student.getStudentName());
System.out.print(" Age:"+ student.getStudentAge());
System.out.println();
}
entr.commit();
System.out.println("success");
}
catch (Exception e)
{
e.printStackTrace();
} finally {
entityManager.close();
}
}
}
Below is The Expection:
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.demo.entities.Student
at com.demo.action.StudentGrouping.main(StudentGrouping.java:28)
My POJO class Fields are:
#Column(name = "studentName")
private String studentName;
#Column(name = "studentAge")
private int studentAge;
Is my GROUP BY clause query is wrong.
Student student = (Student) iterator.next(); is the problem as you aren't actually pulling back an entire student.
SELECT student.studentName, SUM(student.studentAge) FROM Student
student GROUP BY student.studentName
Your query is pulling back these two fields. If you want to map to a student object, you'd have to use the following.
FROM Student student
Then do the calculation by hand on the data. If you wanted to use your original query, you'd have to parse each individual value with, rather than using iterator lets say they were in a resultList.
for (Object[] result : resultList) {
String studentName = (String) result[0]
Integer age = (Integer) result[1];
}
This is because I am sure that you Student class does not look like
String studentName;
Integer yyyy;
which is what you are getting when you ask for
student.studentName, SUM(student.studentAge)
I suggest that you either create a class that looks like your result, or just treat the result as an Object[]
As in
Object student[] = (Object[])iterator.next();
System.out.print("Student Name:"+student[0]);
System.out.print("Max Age:"+student[1]);
Unless you have defined the Student class to be a String and a number, you're not getting back a Student class, so you can't cast it to that in this line:
Student student = (Student) iterator.next();
That, and you probably should also define what kind of classes your List and Iterators are handling.
The problem is you are actually not selecting the student instead you are trying to select custom values from student.
try this:
First create a constructor inside the entity with two param ie. the name and age.
then use this query:
SELECT NEW com.sample.Student(student.studentName, SUM(student.studentAge)) FROM Student student GROUP BY student.studentName;
You need to specify the full class name (sample:com.sample.Student) in the query

Categories