I want to search ExArrayList for a specific gpa? I want an answer of true or false if it exists in ArrayList.
public class ExArrayList {
private String Name;
private double GPA;
public ExArrayList(String name, double gpa) {
this.Name = name;
this.GPA = gpa;
}
public void setGPA(double gpa) {
this.GPA = gpa;
}
public double getGPA() {
return GPA;
}
public void setName(String name) {
this.Name = name;
}
public String getName() {
return Name;
}
#Override
public String toString() {
return String.format("%s\t%f", this.Name, this.GPA);
}
}
public class Main {
public static void main(String[] args) {
ArrayList<ExArrayList> psy101 = new ArrayList<>();
psy101.add(new ExArrayList("Bob", 2.9 ));
psy101.add(new ExArrayList("Steve", 3.9 ));
psy101.add(new ExArrayList("Charles", 4.0 ));
System.out.println();
System.out.printf("Student\tGPA\n");
for(ExArrayList s : psy101) {
System.out.printf("%s\n", s);
}
boolean binFound = psy101.contains(2.9); // This is what I am using to search the ArrayList. It's not working.
System.out.println("Does the list contain GPA of 2.9? " + binFound);`
You could steam the list and use a lambda to look for matches:
boolean binFound = psy101.stream().anyMatch(g -> g.getGPA() == 2.9);
You have to do a compare in the for each loop.
if(s.getGPA == 2.9){
binFound = true;
break;
}
Without Java8 Streams:
boolean binFound = false;
for(ExArrayList exArrayList : psy101) {
if(exArrayList.getGPA() == 2.9) {
binFound = true;
break;
}
}
System.out.println(binFound);
With Java8 Streams:
boolean binFound = psy101.stream().map(ExArrayList::getGPA).
anyMatch(gpa -> gpa == 2.9);
System.out.println(binFound);
I did not like any of these answers. People forgot about the precision errors that occur when trying to compare doubles. I know it should not be too bad for GPA purposes because there isn't a lot of precision involved. However, there is the OK way or the right way of doing things.
See this and this for clarification.
The right way of doing what you are planning is with binary search. But, first the list need to be sorted for it to work.
How to sort Objects in Java? You need to know first how to compare their values and there are a couple of ways of doing this. For my example, I will use Comparable. Check this for learning purposes.
Use this import before anything
import java.util.*;
Now, we implement Comparable in your object. It will look like this after the changes:
public class ExArrayList implements Comparable<ExArrayList> {
private String Name;
private double GPA;
public ExArrayList(String name, double gpa) {
this.Name = name;
this.GPA = gpa;
}
public void setGPA(double gpa) {
this.GPA = gpa;
}
public double getGPA() {
return GPA;
}
public void setName(String name) {
this.Name = name;
}
public String getName() {
return Name;
}
#Override
public String toString() {
return String.format("%s\t%f", this.Name, this.GPA);
}
//new stuff needed to compare the objects
public int compareTo(ExArrayList other) {
return Double.compare(this.GPA, other.GPA);
}
}
Now we can sort your list by doing:
Collections.sort(psy101);
After sorting it, we can search the index of the object by doing:
//here we must pass a fake object with the value that we are trying to find
int index = Collections.binarySearch(psy101, new ExArrayList(null, 2.9));
System.out.println(index >= 0 ? "True" : "False");
index contains the position of 2.9 in the list which is 0, if not found it will contain a negative number.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
Need to find the common objects between to arraylist. Both of them are VarList type which is the simple POJO class. My comparison return all the elements inside the database list , Need to have a common elements (which as you can see they are objects) between two arraylists and add the them into the new list.
VarList class
public class VarList {
private int number;
private int age;
private String name;
public VarList(int number, int age, String name) {
super();
this.number = number;
this.age = age;
this.name = name;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
my solution which has a problem
//database arraylist
ArrayList<VarList> database=new ArrayList<VarList>();
database.add(new VarList(105,19,"b"));
database.add(new VarList(101,18,"c"));
database.add(new VarList(106,54,"database"));
//object array list
ArrayList<VarList> object=new ArrayList<VarList>();
object.add(new VarList(105,19,"b"));
database.add(new VarList(106,54,"database"));
List<VarList> resultList = new ArrayList<VarList>();
for(VarList user1 : database) {
for(VarList user2 : object) {
if(user1.getName().equals(user2.getName())) {
resultList.add(user2);
}
System.out.println(resultList);
}
}
Override equals & hashCode
You need to define overrides of equals and hashcode methods in your VarList class. Your class inherits these methods from Object.
Also, think harder about naming things. The VarList class is not a list, it is an element in your list. Surely it has an actual descriptive name. The second ArrayList you declare is named 'object'?!? Please don't name things object, ever. Call it testList or something.
Finally, your System.out is inside the resultList loop, so its output is likely to confuse you. Or maybe that was intentional. Just realize that it's going to output it once for every element in resultList.
Instead of implementing your own for loop to compare the elements of 2 ArrayList, you could use retainAll(list) method of the Collection class.
Here is the sample Usage:
SimplePojo.java
import java.util.Objects;
public class SimplePojo {
private String name;
private int age;
public SimplePojo(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
#Override
public String toString() {
return "SimplePojo{" + "name='" + name + '\'' + ", age=" + age + '}';
}
#Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SimplePojo that = (SimplePojo) o;
return age == that.age && Objects.equals(name, that.name);
}
#Override
public int hashCode() {
return Objects.hash(name, age);
}
}
Client.java
import java.util.ArrayList;
import java.util.List;
public class ListCommonElements {
public static void main(String[] args) {
List<SimplePojo> list1 = new ArrayList<>();
list1.add(new SimplePojo("Dave",49));
list1.add(new SimplePojo("Smith",40));
list1.add(new SimplePojo("Johnson",32));
System.out.println("List 1: " +list1.toString());
List<SimplePojo> list2 = new ArrayList<>();
list2.add(new SimplePojo("Dave",49));
list2.add(new SimplePojo("Smith",40));
list2.add(new SimplePojo("Steve",32));
System.out.println("List2: "+list2.toString());
list1.retainAll(list2);
System.out.println("Common ELements: " + list1.toString());
}
}
Notice How I am overriding equals and hashCode method (You can autogenerate it if using IntelliJ ).
The reason to do it is your list is not of primitive type, so you need to tell what does equal mean to you (so you can get common elements ) and in the current implementation, I am saying that if both name and age are the same then only I would call 2 Object equal.
I'm trying to compare a bunch of Objects of the same class to search for matching ID's?
This is the GroupClass, when a new entry is entered it will test against the idNumber to see if there is a match.
Public GroupClass {
private int idNumber;
private String name;
private double income;
public GroupClass(int id, String name, double income){
this.idNumber = id;
this.name = name;
this.income = income;
}
public int getIdNumber() {
return idNumber;
}
public void setIdNumber(int idNumber) {
this.idNumber = idNumber;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getIncome() {
return income;
}
public void setIncome(double income) {
this.income = income;
}
}
This is the Main Method
import static java.lang.reflect.Array.set;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
public class ListTester {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Set<GroupClass> groupArray = new LinkedHashSet<>();
System.out.println("Enter a ID Number");
int id = input.nextInt();
System.out.println("Enter a First Name");
String name = input.next();
System.out.println("Enter a an Income");
double income = input.nextDouble();
groupArray.add(new GroupClass(1111, "Billy", 178000));
groupArray.add(new GroupClass(1112, "Sam", 78000));
groupArray.add(new GroupClass(1113, "Mark", 79000));
groupArray.add(new GroupClass(id, name, income));
printTheClass(groupArray);
}
public static void printTheClass(Set group){
for(Object theArray: group){
System.out.println(theArray + " ");
}
}
}
Ive seen a few questions like it but just cant get it to work for my particular case, thanks in advance.
As per the above comment you override the equals method, but this may not be suitable for the long term growth of the class.
But using your existing code try
public static void printTheClass(Set<GroupClass> group){
for(GroupClass theArray: group){
System.out.println(theArray + " ");
}
}
and
public static GroupClass findTheClass(Set<GroupClass> group, int id){
for(GroupClass obj: group){
if(obj.getIdNumber == id) return obj;
}
return null;
}
This can be used as
if (findTheClass (groupArray, id) == null) {
groupArray.add (new GroupClass(id, name, income));
}
Not quite sure what is your goal. If you want to reject any new entry if the id already exist, you need to override the hashCode and equals methods of the GroupClass so that LinkedHashSet knows if two GroupClass objects are different:
#Override
public int hashCode() {
return this.idNumber;
}
#Override
public boolean equals(Object obj) {
return obj instanceof GroupClass && ((GroupClass) obj).getIdNumber() == this.idNumber;
}
However, in most cases, you might want to retrieve an entry using its id number. Then it might be better to use a map with id as key, and the GroupoClass object itself as value
Map<Integer, GroupClass> groupmap = new HashMap<>()
groupmap.put(id, new GroupClass(id, name, income));
and you will have to use groupmap.keySet() to iterate the map.
I'm new to Java and i've been bashing my head over the wall to solve this problem. Anyway below is a class that creates a Person and below that, is a class that creates a Phonebook using an ArrayList of type Person. I want to write the remove function (in order to remove a Person from the list) but my problem is that since i only get the name of the person i can't use the Indexof function (cause it requires object) to get at what position lies the name.
This is my first time using an ArrayList to store an Object so i'm not even sure
how my results would appear. I'm guessing that if the position of the name (in my list) is 10 then 11 would be the phone and 12 would be the address. Am i correct?
public class Person
{
private String name;
private String phone;
private String address;
public Person (String n, String p, String a)
{
this.name = n;
this.phone = p;
this.address = a;
}
public void setPhone(String newPhone)
{
this.phone = newPhone;
}
public String getName()
{
return this.name;
}
public String getPhone()
{
return this.phone;
}
public String getAddress()
{
return this.address;
}
public String print()
{
return "Name is : " + this.name + "\nPhone is : " + this.phone + "\nAddress is : " + this.address;
}
}
import java.util.*;
public class phoneBook
{
Scanner in = new Scanner ( System.in );
private ArrayList <Person> persons = new ArrayList <Person>();
private int i;
private boolean flag;
public void addPerson(Person p)
{
persons.add(p);
}
public void listPersons ()
{
System.out.println(persons);
}
public void lookUp (String theName)
{
flag = persons.contains(theName);
if ( flag == true )
{
System.out.println("That name exists!");
}
else
{
System.out.println("That name does not exist!");
}
}
public void remove (String theName)
{
}
Edit: I'm planning to use the Scanner in another function. Don't worry about it.
I'm not sure of if do you want to get the object of that array, but each object is indexed to that array (with full attributes), now you can remove it by using the following code,
public String removePerson(ArrayList<Person> arrayList,String name)
{
for(Person currentPerson:arrayList)
{
if(currentPerson.getName().equals(name))
{
arrayList.remove(currentPerson);
return "Removed successfully"
}
}
return "No record found for that person";
}
just pass the arrayList and the name of that person to this method
You should override the equals() and hashCode() methods in the Person class. This way you will define when two objects of this type will be considered equal. Then you can use list.contains(yourObject) to determine if that object is equal to any object in your list, this based on your equals() implementation.
Does this help you?
public void remove (String theName,ArrayList<Person> persons) {
for (int i = 0; i < persons.size();++i) {
if(persons[i].getName().equals(theName)) {
persons.remove(i);
}
}
}
Best regards, Nazar
I'm trying to find out how to make separate toString methods based on an overloaded constructor. Take the below code for example:
public class Employee {
private double salary;
private String name;
public Employee(String name) {
this.name = name;
}
public Employee(String name, int salary) {
this.name = name;
this.salary = salary;
}
}
Now, I would like to implement a toString method that is dependent on the object created and output the corresponding values.(i.e. one that outputs just name, the other that outputs name and salary) Do I need only one toString method and need to add an if-else statement?
Sorry if this is a silly question, I'm just learning the ropes of Java.
You can only have one toString(), but you can determine the object's "state" and put together the string accordingly. For instance, you can have a salary of -1 indicate that the first constructor was called. Therefore, your toString() would look like:
#Override
public String toString() {
if (salary < 0) {
...
} else {
...
}
}
Don't forget to set salary to -1 in the first constructor.
Well what you are doing here is just instantiating constructors, which has nothing to do with any methods. Constructors just help you initialize and sort of provide context to variables that you will be working with.
If as you said, printing or output-ing the salary and name, you would have to create methods like:
public String printName(){
return name;
}
public String printAll(){
return name + "" + String.valueOf(salary);
}
First, make your salary a negative double (hopefully no one pays to work)... then, default your name field to null. Finally, check for nulls (or negative) in toString(). So, something like this -
private double salary = -1;
private String name = null;
public Employee(String name) {
this.name = name;
}
public Employee(String name, double salary) { // <-- salary isn't an int.
this.name = name;
this.salary = salary;
}
public String toString() {
StringBuilder sb = new StringBuilder();
if (name != null) {
sb.append(name);
if (salary > 0) { // = only if both are valid.
sb.append(" = ");
}
}
if (salary > 0) {
sb.append(salary);
}
return sb.toString();
}
I am fairly new to Java and I have exhausted all of my current resources to find an answer. I am wondering if it possible to access an Objects first property to see if it matches a particular integer?
For example, I am trying to obtain a Product that is within my Database by searching for it by it's Product ID. Therefore, if I create two products such as, Product ipad = new Product(12345, "iPad", 125.0, DeptCode.COMPUTER); and Product ipod = new Product(12356, "iPod", 125.0, DeptCode.ELECTRONICS); (I have included this Product class below), and add them to an Arraylist such as, List<Product> products = new ArrayList<Product>(); how can I loop through this ArrayList in order to find that product by its ID?
This is the method I am working on:
List<Product> products = new ArrayList<Product>();
#Override
public Product getProduct(int productId) {
// TODO Auto-generated method stub
for(int i=0; i<products.size(); i++){
//if statement would go here
//I was trying: if (Product.getId() == productId) {
System.out.println(products.get(i));
}
return null;
}`
I know that I can include a conditional statement in the for loop but I cant figure out how to access the getId() method in the Product class to compare it the productId parameter?
package productdb;
public class Product {
private Integer id;
private String name;
private double price;
private DeptCode dept;
public Product(String name, double price, DeptCode code) {
this(null, name, price, code);
}
public Product(Integer id, String name, double price, DeptCode code) {
this.id = id;
this.name = name;
this.price = price;
this.dept = code;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public DeptCode getDept() {
return dept;
}
public void setDept(DeptCode dept) {
this.dept = dept;
}
public void setName(String name) {
this.name = name;
}
public void setPrice(double price) {
this.price = price;
}
#Override
public String toString() {
String info = String.format("Product [productId:%d, name: %s, dept: %s, price: %.2f",
id, name, dept, price);
return info;
}
}
Please let me know
You have already got the Product out of the List<Product> in the following statement:
System.out.println(products.get(i));
Now, that you have got Product, now to get it's id, you can just call it's getId() method:
if (product.get(i).getId() == productId) {
// Return this product.
}
I would also suggest you to use enhanced for-loop instead of the traditional loop like this:
for (Product product: products) {
// Now you have the product. Just get the Id
if (product.getId() == productId) {
return product;
}
}
Also, you should change the type of productId from Integer to int. You don't need a wrapper type there.
Have you considered using a HashMap (or LinkedHashMap) instead of an Array. This way you can use the productId as the key and the product as the value?
This will let you get the object without having to loop through the entire array.
For comparing the ArrayList Objects make override equal function in your CustomObject Class Like Employee.
ArrayList<Employee> list;
Employee emp;
//suppose you have some number of items in that list and emp object contains some value.
int size=list.size();
for(int i=0;i<size;i++) {
if(list.get(i).equals(emp)) {
//todo perform operation on the basis of result.
}
}
And suppose this is your Employee class and in that class you need to override the equal function.
class Employee{
int age;
String name;
public int getAge() {
return this.age;
}
public String getName() {
return this.name;
}
public void setAge(int emp_age) {
this.age=emp_age;
}
public void setName(String emp_name) {
this.name=emp_name;
}
#Override
public boolean equal(Employee emp) {
boolean isEqual=false;
if(emp!=null && emp instanceof Employee) {
isEqual=(this.age==emp.age);
}
return isEqual;
}
}
I hope this solution will help you to check for equal values and compare the values.
Thanks
According to your commented line //I was trying: if (Product.getId() == productId) I think where you were falling over is using Product (capital P). What you needed was:
if (products.get(i).getId() == productId)
Also, you weren't returning the product you found...
The problem with that form is that a) you have to find the product in the list twice (once in the condition and then again when printing the result - a third time if you returned the product) and b) it will throw a null pointer exception if the product you are looking for is not in the list.
This is a nicer, more compact way of doing it:
#Override
public Product getProduct(int productId)
{
for(Product product : products)
{
if (productId == product.getId())
{
System.out.println(product.toString());
return product;
}
}
return null;
}