Inputting strings into arrayLists? - java

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.

Related

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;
}

Ignore parameter in getBy****() function in MongoRepository

I'm using MongoRepository in my service. In my case, I have three field whose names are "Name", "Age" and "Gender". I could have following methods in my interface to query the data:
List<People> getByName(String name);
List<People> getByAge(String age);
List<People> getByNameAndGender(String name, String gender);
...and so on...
Now I want to query data with every combination of these 3 fields, so I need to write 7 (3 + 3 + 1) methods here and it is really ugly.
I tried to write something like
List<People> getByNameAndAgeAndGender(String name, String age, String gender);
And if the input has only two fields: name = Chris, age = 18, then I could call
List<People> peoples = getByNameAndAgeAndGender("Chris", "18", "*")
to get the list of people whose name is Chris and age is 18. How can I achieve this goal? I really don't want to write a big "if...else if...else if..." body. Thank you!
Try this:
List<People> getByNameLikeAndAgeLikeAndGenderLike(String name, String age, String gender);

Use a Object by String?

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.

Returning all the keys from a HashMap withou looping

I am attemping to populate a JComboBox with the names of cities.
My program has a class called 'Country'. The Country object contains a HashMap of objects called 'City' with a method getName, returning a String value.
public class Country {
private final Map<String, City> cities = new HashMap<>();
public Collection<City> getCities() {
return cities.values();
}
}
public class City {
String cityName;
public String getName() {
return cityName;
}
}
Is it possible to return an String array of cityName without using a loop? I was trying the following but it did not work:
Country country 1 = new Country();
String[] cityNames = country1.getCities().toArray();
JComboBox cityChoice = new JComboBox(cityNames);
This returns an Array of City objects, however I am not sure how to use the City getName method in conjunction with this.
You can not avoid looping. Either, you will loop, or Java will loop in the background.
You can avoid writing your own loop if keys in your map are city names. Then, you could only ask .keySet() from the map. But, even in that case, Java would loop in the background and copy the keys.
Other way is that you loop, but hide the loop in some method (lets say getCitiesArray()) in the class. So, you could do country1.getCitiesArray(); in the calling method. Code would look better and be easier to read, but you would still need to have loop inside of the class.
You can store Map key as CityName then do below to get Names.
cities.keySet();
The city object can be used directly in the combobox with some minor alterations.
public class City {
String cityName;
public String getName() {
return cityName;
}
#Override
public String toString() {
return getName();
}
}
Then the population code
Country country1 = new Country();
City[] cities = country1.getCities().toArray();
JComboBox<City> cityChoice = new JComboBox<City>(cities);
You should probably override hashCode and equals also.
If you are using Java 8, you can use the Stream API to map the names of the cities to a String:
String []cityNames = country1.getCities().stream().map(City::getName).toArray(String[]::new);

Different collections for different data sorting

I have a task to play with Java Collections framework. I need to obtain a users list from a database, and store it in a collection. (This is finished and users are stored in a HashSet). Each user is an instance of Person class described with name, surname, birth date, join date, and some other parameters which are not important now. Next I need to store the list in different collections (there's nowhere stated how many) providing functionality to sort them by:
- name only
- name, surname, birthdate
- join date
Ok, so to start with, my Person stores data as Strings only (should I change dates to Date ?). I've started implementing sorting with "by name, surname, birthdate", cause that's what I get after calling sort on list with Strings. Am I right ?
public List createListByName(Set set){
List ret = new ArrayList<String>();
String data = "";
for(Object p: set){
data = p + "\n";
ret.add(data);
}
Collections.sort(ret);
return ret;
}
But what with the rest ? Here's my Person :
class Person {
private String firstname;
private String lastname;
)..)
Person(String name, String surname, (..)){
firstname = name;
lastname = surname;
(..)
}
#Override
public String toString(){
return firstname + " " + lastname + " " + (..);
}
}
I wouldn't convert everything to strings to start with. I would implement Comparator<Person> and then sort a List<Person>:
public List<Person> createListByName(Set<Person> set){
List<Person> ret = new ArrayList<Person>(set);
Collections.sort(ret, new NameSurnameBirthComparator());
return ret;
}
The NameSurnameBirthComparator would implement Comparator<Person> and compare two people by first comparing their first names, then their surnames (if their first names are equal) then their birth dates (if their surnames are equal).
Something like this:
public int compare(Person p1, Person p2) {
// TODO: Consider null checks, and what to do :)
int firstNameResult = p1.getFirstName().compareTo(p2.getFirstName());
if (firstNameResult != 0) {
return firstNameResult;
}
int surnameResult = p1.getSurname().compareTo(p2.getSurname());
if (surnameResult != 0) {
return surnameResult;
}
return p1.getBirthDate().compareTo(p2.getBirthDate());
}
And yes, I would store the date of birth as a Date - or preferably as a LocalDate from JodaTime, as that's a much nicer library for date and time manipulation :)
so I should write multiple comprators on Person for each task ?
Given this is a homework task, then I would say that is the way you would start to learn about Comparators.
For interest sake only you can do this by creating a couple of resuable Comparators.
You can use the Bean Comparator to sort on individual properties.
Then you can use the Group Comparator to sort on multiple properties.

Categories