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;
}
Related
In command prompt I enter the following:
db.products.insert( { item: "card", qty: 15 } )
I wanted to know how would I be able to get the item value from java.
I want to create a variable called item and it would know the value of it which is "card".
I am currently using MongoOperations in java but I do not know how to get only one value from MongoDB.
Pojo
#Document(collection="products")
public class ValueServerModel{
#Id
private String id;
String item;
int qty;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
public Product(String item, int qty) {
//super();
this.item = item;
this.qty = qty;
}
#Override
public String toString() {
return "Product [id=" + id + ", item=" + item + ", qty=" + Integer.toString(qty) + "]";
}
}
//provided by suwal
Long Shot Attempt
#Autowired
MongoOperations mongoOperations;
#PostConstruct
public List<SomeModel> getList() {
List<SomeModel> pmLst = mongoOperations.findAll(ServerModel.class);
//code above works I get a list of values based on mongo db
//attempting to retrieve one value, (stuck)
String value = mongoOperations.find("test", ValueServerModel.class);
With command prompt
I am able to get a value by using the following command:
db.products.find({}, {qty:0, _id:0})
//output ("item": "card")
I want to achieve the following:
db.products.find({}, {item})
//output should be "card".
is it possible to do what I just did above?
You can use projection to request the fields.
Something like
Query query = new Query();
query.fields().include("item").exclude("_id");
Product product = mongoOperations.findOne(query, Product.class);
This will populate the product pojo with item field.
You can use native mongo java driver to request the fields directly.
Something like
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
MongoDatabase database = mongoClient.getDatabase(db_name);
MongoCollection<Document> collection = database.getCollection(collection_name);
String value = collection.find().projection(Projections.include("item")).first().getString("item");
I get that you want to get the value, but you are not specifying based on what. That is "what is your query condition". Also not sure what ServerModel and ValueServerModel classes are, but let see if this general idea helps you.
Lets say you have following structure stored after your insert query in the collection products
{
"_id" : ObjectId("5939d5a1d0ffa3f0209fd42f"),
"item" : "card",
"qty" : 15
}
You will need a model representing the collection,
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
#Document(collection="products") //this is what binds this class to your collection
public class Product {
#Id
private String id;
String item;
int qty;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
public Product(String item, int qty) {
//super();
this.item = item;
this.qty = qty;
}
#Override
public String toString() {
return "Product [id=" + id + ", item=" + item + ", qty=" + Integer.toString(qty) + "]";
}
}
Now in your code you would have something like this,
// findOne returns you single instance of an object of the specified type
Product product = mongoOperation.findOne(
new Query(Criteria.where("item").is("card")), Product.class);
System.out.println(product); //Output => Product [id=5939d5a1d0ffa3f0209fd42f, item=card, qty=15]
String value = product.getItem();
System.out.println("value is " + value);//Output => card
Lets say you want to get by id instead, so you would have something like this
Product product2 = mongoOperation.findOne(
new Query(Criteria.where("_id").is("5939d5a1d0ffa3f0209fd42f")),
Product.class);
System.out.println(product2);
when i trying to do this i got the problem said
Constructor Product in class Product cannot be applied to given types;
required: java.lang.String,int,double; found: java.lang.String;
reason: actual and formal arguments lists differ in length
And i have 2 classes:
import java.text.*
public class Product {
private String name;
private int stock;
private double price;
public Product(String name, int stock, double price) {
this.name = name;
this.stock = stock;
this.price = price;
}
public double sell(int n) {
stock = n;
return stock;
}
public void restock(int n) {
}
#Override
public String toString() {
return stock + name + "at $"+price;
}
}
public class Store {
public static void main(String[] args) {
new Store().use();
}
private Product product;
private Product cashRegister;
public Store() {
product = new Product("Sticky tape");
cashRegister = new Product("Cash register");
}
public void use() {
}
private void sell() {
}
private void restock() {
}
private void viewStock() {
}
private void viewCash() {
}
private void help() {
System.out.println("Menu options");
System.out.println("s = sell");
System.out.println("r = restock");
System.out.println("v = view stock");
System.out.println("c = view cash");
System.out.println("x = exit");
}
}
I understand that i have to declare for Product constructor. But i think i have done it. If anyone know where i got wrong please explain. Thank you!
you do not have constructor with one param, so you can not using this form
product = new Product("Sticky tape");
decare one more constructor with one param or fill all param
product = new Product("Sticky tape", 10, 20.0);
You need to:
overload the constructor
public Product(String name){...}
or create instances of Product using the right and only one constructor uor have:
public Product(String name, int stock, double price)
if you overload then something like this should happen
public Product(String name){
this(name, 0, 0.0);
}
so you call a constructor from the other constructor
This is the time to learn constructor overloading. Overloading comes from OOP.
You can use Overloading to methods and constructors. Overloading means for a same method name you can implement that method
several time with different parameters(number of parameters)
. Actualy not only that,
you can use different data types for parameter.
also can change order of parameter.
keep remember method name must be same.
For the constructor also same thing. If you use for constructor you can add parameters like:
//constructor with one parameter
public Product(String name) {
this.name = name;
this.stock = 0;//or whatever your default value
this.price = 0;//or whatever your default value
}
//constructor with two parameter
public Product(String name, , int stock) {
this.name = name;
this.stock = stock;
this.price = 0;//or whatever your default value
}
public Product(String name, int stock, double price) {
this.name = name;
this.stock = stock;
this.price = price;
}
Like that you can add as many as you want.
Or you can use one constructor and pass argument to match with the implementation of the constructor when creating object. Like below:
product = new Product("Sticky tape", 0, 0);
this is not complete description you can read this to learn more
You have no constructor In Product class that takes single String argument. Create it like so:
public Product(String name) {
this.name = name;
}
In import statement you forgot semicolon:
import java.text.*;
your program is having 3 coding error which include
you forgot the " ; " after " import java.text.* " actually it is not required in your code, you can remove it, nothing will change.
you cannot make class Product as public , because you've made "Store" as your Primary class having main method.So remove public keyword from the Product class.
You didn't create a parameterized constructor
which should be like
public Product(String name){ this.name = name;}
in your product class.
your code will be like after correcting
class Product {
private String name;
private int stock;
private double price;
public Product(String name, int stock, double price) {
this.name = name;
this.stock = stock;
this.price = price;
}
public Product(String name) {
this.name = name;
}
public double sell(int n) {
stock = n;
return stock;
}
public void restock(int n) {
}
#Override
public String toString() {
return stock + name + "at $"+price;
}
}
public class Store {
public static void main(String[] args) {
Store s = new Store();
System.out.println(s.product);
System.out.println(s.cashRegister);
}
private Product product;
private Product cashRegister;
public Store() {
product = new Product("Sticky tape");
cashRegister = new Product("Cash register");
}
}
The errors are in these lines of code:
product = new Product("Sticky tape");
cashRegister = new Product("Cash register");
The Product constructor defined expects:
public Product(String name, int stock, double price)
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.
I have two ArrayList.
private ArrayList<Friend> friendsList = new ArrayList<Friend>();
private ArrayList<Friend> myFriendsList = new ArrayList<Friend>();
First one contains all Friend of database. Second one contains only user Friend. In my search option(SearchManager) i've a ListView contains searched friends of friendsList. When i select a Friend of ListView, i want to check if the Friend exists in myFriendsList. I used following code
friendListView
.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
handelListItemClick(adapter.getItem(position));
}
});
private void handelListItemClick(Friend friend) {
for(Friend fr: myFriendsList){
Log.v("Check User Name:", fr.getName());
}
if (myFriendsList.contains(friend)) {works with matched friend}
But it can't check the selected Friend in myFriendsList. In LogCat it show myFriendsList information. Thanks in advance.
Update
Here is my Friend class
public class Friend {
private String id, name, thumbnailUrl;
public Friend() {
}
public Friend(String name, String thumbnailUrl) {
this.name = name;
this.thumbnailUrl = thumbnailUrl;
}
public Friend(String name, String thumbnailUrl, String id) {
this.name = name;
this.thumbnailUrl = thumbnailUrl;
this.id = id;
}
public String getID(){
return id;
}
public void setID(String id){
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getThumbnailUrl() {
return thumbnailUrl;
}
public void setThumbnailUrl(String thumbnailUrl) {
this.thumbnailUrl = thumbnailUrl;
}
}
To be able to use methods to find and search like contains your custom class MUST implement correctly the hasCode and equals methods.
Here is the link about the implementing hasCode and here about implementing equals. It is Java Best Practises website that I like very much and from where I've learned about it.
equals() is used in most collections to determine if a collection contains a given element
hashCode() of this object is calculated and used to determine where to search for the object in the hash tables.
For more information on either of these topics visit oracle webiste or take a look here
If You could decide that two Friend objects are equal to each other if just their id's are equal.
So , In your Friend Class include
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Friend)) return false;
Friend friend = (Friend) o;
if (!id.equals(friend.id)) return false;
return true;
}
#Override
public int hashCode() {
return id.hashCode();
}
Now just do,
private void handelListItemClick(Friend friend) {
if (myFriendsList.contains(friend)) {works with matched friend}
}
Edit
You can take a look at this tutorial to learn more about the topic
I have a class named Person.This class represents (as the name says) a Person. Now I have to create a class PhoneBook to represent a list of Persons. How can I do this? I don't understand what means "create a class to represent a list".
import java.util.*;
public class Person {
private String surname;
private String name;
private String title;
private String mail_addr;
private String company;
private String position;
private int homephone;
private int officephone;
private int cellphone;
private Collection<OtherPhoneBook> otherphonebooklist;
public Person(String surname,String name,String title,String mail_addr,String company,String position){
this.surname=surname;
this.name=name;
this.title=title;
this.mail_addr=mail_addr;
this.company=company;
this.position=position;
otherphonebooklist=new ArrayList<OtherPhoneBook>();
}
public String getSurname(){
return surname;
}
public String getName(){
return name;
}
public String getTitle(){
return title;
}
public String getMailAddr(){
return company;
}
public String getCompany(){
return position;
}
public void setHomePhone(int hp){
homephone=hp;
}
public void setOfficePhone(int op){
officephone=op;
}
public void setCellPhone(int cp){
cellphone=cp;
}
public int getHomePhone(){
return homephone;
}
public int getOfficePhone(){
return officephone;
}
public int getCellPhone(){
return cellphone;
}
public Collection<OtherPhoneBook> getOtherPhoneBook(){
return otherphonebooklist;
}
public String toString(){
String temp="";
temp+="\nSurname: "+surname;
temp+="\nName: "+name;
temp+="\nTitle: "+title;
temp+="\nMail Address: "+mail_addr;
temp+="\nCompany: "+company;
temp+="\nPosition: "+position;
return temp;
}
}
Your PhoneBook class will likely have a member like this:
private List<Person> book = new ArrayList<Person>();
And methods for adding and retrieving Person objects to/from this list:
public void add(final Person person) {
this.book.add(person);
}
public Person get(final Person person) {
int ind = this.book.indexOf(person);
return (ind != -1) ? this.book.get(ind) : null;
}
Note that a List isn't the best possible representation for a phone book, because (in the worst case) you'll need to traverse the entire list to look up a number.
There are many improvements/enhancements you could make. This should get you started.
Based on the class being named PhoneBook, I assume that you ultimately want to create a mapping between a phone number, and a person. If this is what you need to do then your PhoneBook class should contain a Map instead of a List (but this may depend on other parameters of the project).
public class PhoneBook
{
private Map<String,Person> people = new HashMap<String,Person>();
public void addPerson(String phoneNumber, Person person)
{
people.put(phoneNumber,person);
}
public void getPerson(String phoneNumber)
{
return people.get(phoneNumber);
}
}
In the above, the phone number is represented as a String, which is probably not ideal since the same phone number could have different String representations (different spacing, or dashes, etc). Ideally the Map key would be a PhoneNumber class that takes this all into account in its hashCode and equals functions.
you can do it by creating a class PhoneBook
public class PhoneBook{
Private List<Person> personList = new ArrayList<Person>;
public void addPerson(Person person){
this.personList.add(person);
}
public List getPersonList(){
return this.personList;
}
public Person getPersonByIndex(int index){
return this.personList.get(index);
}
}