I have situation where I have a list(required items) that holds a table column result like:
NAME
ADDRESS
AGE
.
.
etc
In my method I get a User object that contains values for user.getName(), user.getAge() etc. I want to know the best way to ensure that every item in the list is present in the user object. The no of items in the list are variable.
public boolean isUserInfoComplete(User user, ArrayList list){
//so, if the list has AGE, the user.getAge() must have some value
}
One way I thought of is maintaining another list that holds values of every user info and checking that against my db list but that is not scalable.
It's not possible to dynamically match your method names with the list contents without reflection (which can be expensive and fragile). You may want to consider keeping your User values in a central Map cache. Here's one way to do that:
public class User {
private enum Field {
NAME,
AGE
//...
}
private Map<String, Object> values = new HashMap<>();
private void putValue(Field field, Object value) {
values.put(field.name(), value);
}
private Object getValue(Field field) {
return values.get(field.name());
}
public void setName(String name) {
putValue(Field.NAME, name);
}
public String getName() {
return (String)getValue(Field.NAME);
}
public void setAge(int age) {
putValue(Field.AGE, age);
}
public Integer getAge() {
return (Integer)getValue(Field.AGE);
}
//...
public boolean isUserInfoComplete(List<String> fields) {
return values.keySet().containsAll(fields);
}
}
You could use reflection to solve this problem if the items in the list match the getters in your User object.
For example, if AGE is in the list, you could use reflection to look for the getAge() method on the User class, call it on the object, and then check the result for null (or switch on the method return type to perform other types of checks).
Here's a starting point for you to experiment with (I haven't compiled or tested it):
public boolean isUserInfoComplete(User user, ArrayList list){
for(String attribute : list) {
String methodName = "get" + attribute.substring(0, 1).toUpperCase() + attribute.substring(1).toLowerCase();
Method method = User.class.getMethod(methodName, null);
if(method != null) {
Object result = method.invoke(user);
if(result == null) {
return false;
}
}
}
return true;
}
This seems like a case where you need reflection. This gives you the opportunity to inspect methods and field from your objects at runtime.
If you know your User-objects etc will follow a java bean standard then you will be able to use the getters for checking, though I see now problem in making your fields public final and checking directly on the fields themselves.
Take a look at https://docs.oracle.com/javase/tutorial/reflect/
You can check it using contains() while looping. This process will be very resource-consuming.
Maybe you can redesign something and simply compare two User objects? Will be faster. You can do it by providing your own implementation of equals and hashcode methods.
Related
I have a class of persons.
Public class Person{
private String name = "";
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Now I have another class and inside the class I declared an arraylist
public class AddPerson {
public ArrayList<Person> pers = new ArrayList<Person>();
//here we add some persons to the arraylist
pers.add(new Person("Simon"));
pers.add(new Person("Oscar"));
pers.add(new Person("Alfred"));
String name = "Simon";
pers.contains(name); //return false
pers.equals(name); //return false
//I also want to be able to return the value and index of the name in arraylist if it exsists.
if(pers.contains(name)) //return index and value
}
When I try to check if two strings are equal or if a string is already in my list I get both false. I did some research and I saw that I need to override my equals method (and mabey hash and contains method as well). I do not know how to do it and I could not find a good reference how to do it. Please help me to achive that.
Here the problem is you are comparing a Person object with String object using the contains method.So actually in this case there is no point of implementing equals() method and hashCode() methods or using the contains() method to solve this .Only you have to do is check if person's attribute name is equal to your comparing String called name.
Sample solution:
String name="Simon";
Person result = null;//To store the person object if a person name Simon found in the list
int personIndex = -1; //To store the index of founded person
int indexCount =-1;//To maintain the current index value of arrayList
for(Person tempPerson:pers){//Iterating the list to find a person name Simon
indexCount++;
if(pers.getName().equals(name)){
personIndex = indexCount;
result = tempPerson;
}
}
Now you can use the values in personIndex and indexCount variables for future calculations.You can use a condition like if(personIndex >= 0) to check if really a person found with the comparing name after the iteration and then you can get the result variable value.
That is because you are trying to compare a string ("simon") and an object Person built from a string (Person("Simon")). These are two different objects, and it is thus normal to have false as a result.
Whether you want to compare two Person (this would make sense) or you are actually trying to compare a string and a person are it is most certainly a bad idea (you can't actually compare apples and oranges, well this is the same here).
What you might want to do is whether
to override Person's equals method to, for example, return true if they have the same name. => comparing Persons
to iterate on your pers array and fetch it's name property via getName() to compare it with you name string => comparing Strings
1 =>
#Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final Person person = (Person)o;
return name.equals(person.name);
}
#Override
public int hashCode() {
return Objects.hash(name);
}
2 =>
for (final Person person : pers) {
if(name.equals(person.getName())){
// ...
}
}
I have to do a little exercise (homework, like a friendlist) in Java, and i'm a little stuck on one of the tasks that i have to implement in my program.
The exercise is about storing some friend-objects with a variety of attributes in a container-class and implementing some methods in the container-class for various tasks on the friend-objects.
The overall exercise is not a problem at all, but i'm quite unconvinced that my solution is the way to go. I hope you can give me some tips here.
The method that is left over, should be something like a "updateFriend" method, with which you can set the value of a given attribute to a new value, straight from the container-class.
I've already set up my friend-class with a handfull of attributes (e.g. prename, lastname, date of birth, adress, and so on) an getters/setters for all of them. I've also implemented the container-class (as an ArrayList), but i can't seem to find an elegant way to implement this specific method. My updateFriend()-method right now takes three parameters.
1.The specific id of the friend-object
2.The name of the attribute that i want to change
3.The new value of the attribute
It uses an enum to check if the entered attribute is an existing attribute and if yes, the method searches the ArrayList for the object that contains that attribute and should overwrite the existing value. It gets a little bulky, as i have implemented a switch on the enum, that calls the fitting setter-method for each attribute of the friend, if the type in attribute exists at all.
So basically the friend-class looks like this:
public class Friend {
private static int friendCount = 1;
private String firstname;
private String lastname;
private LocalDate dateOfBirth;
private String phonenumber;
private String mobilenumber;
private String eMail;
private Adress home;
private int friendID;
//Getters & Setters
...
}
The method that gives me problems in the container-class looks something like this at the moment:
public void updateFriend(int id, String toChange, String newValue)
{
for(Attribute a : attribute.values())
{
if(String.valueOf(a).equalsIgnoreCase(toChange))
{
for(Friend f : friends)
{
int counter = 1;
if(f.getID() == id)
{
switch(a)
{
case FIRSTNAME:
{
f.setPreName(neuerWert);
break;
}
//a case for each attribute
}
I'm quite certain that my take on the given method is messy, slow, and cumbersome. What would be an elegant way of solving this?
Excuse my wording and thanks in advance, greets.
I would suggest 3 performance improvements.
Use HashMap instead of List with key as id. Since, id will be unique, it will take O(1) time to get the relevant object for modification instead of spending O(n) time on List iteration.
You can change the type of toChange parameter from String to enum. This will avoid enum to String conversion and then comparing it.
Since, you are already doing validation of the attribute to be modified and you must be following standard java convention while naming your getters and setters, you can use reflection to call the method on the Friend object by creating the method name from attribute name like set{Attributename}.
Okay, lets start using the enum Attribute to handle all the changes (Since you already holding the attribute values)
Attribute Enum
public enum Attribute {
FIRSTNAME("fname", (friend, name) -> friend.setFirstname(String.valueOf(name))),
LASTNAME("lname", (friend, lname) -> friend.setLastname(String.valueOf(lname))),
DATEOFBIRTH("dob", (friend, dob) -> friend.setDateOfBirth((LocalDate) dob)),
PHONENUMBER("pno", (friend, pno) -> friend.setFirstname(String.valueOf(pno))),
MOBILENUMBER("mno", (friend, mno) -> friend.setFirstname(String.valueOf(mno)));
private String attributeName;
private BiConsumer<Friend, Object> attributeSetter;
public static Attribute getAttributeSetterByName(String attributeName) {
return Arrays.stream(Attribute.values())
.filter(attribute -> attribute.getAttributeName().equalsIgnoreCase(attributeName))
.findFirst()
.orElseThrow(() -> new RuntimeException(String.format("Invalid Attribute name - %s", attributeName)));
//.orElse(null);
}
//Getter, Setter & Args Constructor (Use Lombok to reduce Boiler Plate code)
}
Update Logic
public void updateFriend(int id, String toChange, String newValue) {
Attribute attribute = Attribute.getAttributeSetterByName(toChange);
for (Friend friend : friends) {
if (friend.getId() == id) {
attribute.getAttributeSetter().accept(friend, newValue);
break;
}
}
}
You can use a java.util.function.Consumer<T> object to change an object inside your container where you have all the type safety you get. Instead of having magic strings and string arguments for values, which might not be even for string fields, you can work directly on the objects type:
public void updateFriend(int id, Consumer<Friend> c) {
// find the friend object
Friend found = null;
for (Friend f: this.friends) {
if (f.getId() == id) {
found = f;
break;
}
}
if (found == null) {
throw new IllegalArgumentException("There is no friend object with the given id");
}
// use the friend object.
c.accept(found);
}
You can use this method like this:
container.updateFriend(42, f -> f.setVorName("abc"));
container.updateFriend(9, f -> f.setAddress(some_address_object));
How to create a list of maps, where each key name is inferred from name of the class attribute, and value is to be put by getter method
I am having following class in java
class DTA {
private String id;
private String age;
#Override
public String toString() {
return "DTA{" +
"id='" + id + '\'' +
", age='" + age + '\'' +
'}';
}
public DTA(String id, String age) {
this.id = id;
this.age = age;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
I am having a list of objects of type DTA
List<DTA> listA = new ArrayList<>();
listA.add(new DTA("A", "15"));
listA.add(new DTA("B", "25"));
I want to create an ordered list of maps (somewhat like scala) which has following content.
List<? extends Map<String, String>>
List(Map("id"->"A", "age"->"15"), Map("id"->"B", "age"->"25"))
Without "dynamics", the straight forward thing might look like:
List<Map<String, String>> x = listA
.stream()
.map(this::toMap)
.collect(Collectors.toList());
with a local helper, such as:
private Map<String, String> toMap(DTA dta) {
Map<String, String> rv = new HashMap<>();
rv.put("id", dta.getId());
rv.put("age", dta.getAge());
return rv;
}
In order to be fully dynamic here, you would have to use reflection to query the field names. You can find examples how to do that here.
But I strongly suggest to not do that: reflection should always be your last resort. The notion of DTA suggests that you have that object data coming from some "service" anyway. If so, why first serialize into a specific DTA class, to then "flatten" that information into some generic Map structure?!
Meaning: when that service gives you objects that are serialized as, say JSON, or XML ... then it would be much better to simply use a library like gson or jackson to directly deserialize that data into such generic "flat" Map-based objects. Jackson for example has a JsonNode class. When you deserialize into such objects, you get that mapping of field names for free! See here more example code.
The point is: identifying fields using reflection is possible. But reflection code is always tedious, and error prone. If possible, stay away from doing that yourself.
Basically, the tool used to "look into" the contents of classes in Java is called reflection. For example, if your object is a POJO (Plain Old Java Object), you can iterate over all fields in the class in the following way:
DTA obj; // some object, I assume it's initialized
Field[] fields = DTA.class.getDeclaredFields();
Map<String, Object> valuesMap = new HashMap<>();
for (field : fields) {
boolean wasAccessible = field.isAccessible(); // check if class has access control disabled
field.setAccessible(true); // disable access control (private/protected) to extract value
valuesMap.put(field.getName(), field.get(obj));
field.setAccessible(wasAccessible); // return flag to initial value
}
However, accessing values via reflection this way is notoriously hacky. Unless you have good reasons to do it yourself, try using a framework that automates tasks like that rather than writing code like this from scratch.
Also, reflection is slow. Accessing Field entities like that for every single object is suboptimal, if you ever want to really write code like this, you should cache the Field objects in a Map<String, Field> and only do the setAccessible override and the Field retrieval once for every collection of DTA objects.
I am newbie to java, I have a scenario, where i need to list the organisation types from the table:
Requirement : Just listing, no add or removing the elements,
As i understand the difference between set and list:
Set:
Set is Unique collection of Objects.
Set is Un-ordered collection of Objects.
List:
List is non-unique collection of Objects.
List is ordered collection of Objects.
In my table i am having columns like:
id name is_active
1 Lab 1
2 Pharmacy 2
3 Hospital 3
Maximum 10 rows
**Controller**:
List<OrgType> orgTypeList = organizationService.getAllOrgTypes(true);
OrgTypeResponse response = new OrgTypeResponse();
List<EntityDetail> orgTypeDetailList = new ArrayList<>();
EntityDetail orgTypeDetail;
for(OrgType orgType : orgTypeList) {
orgTypeDetail = new EntityDetail();
orgTypeDetail.setId(orgType.getId());
orgTypeDetail.setName(orgType.getName());
orgTypeDetailList.add(orgTypeDetail);
}
response.setStatus(ResponseStatusCode.SUCCESS);
response.setTotalOrgTypes((long)orgTypeDetailList.size());
response.setOrgTypes(orgTypeDetailList);
return response;
**Service** Implementaion:
List<OrgType> orgTypeList = orgTypeRepository.findByActive(active);
return orgTypeList;
This is my EntityDetail class:
public class EntityDetail {
private Long id;
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
My question here is, can i use the Set instead of List
If Set is used, can i use TreeSet, because i need to show in the asc order of id
Or Leave the code, as it is
i just want the clarification,
Thanks
You can use any of them but things to be kept in consideration:
Set although provides unique data, but that also has a cost.
In case, you are sure that table has unique names of organizations then you should opt for list.
It seems like you are using Spring with JPA, if that is the case, then you can use SORT interface(org.springframework.data.domain.Sort) to get sorted data.
My question here is, can i use the Set instead of List
Yes, without problem, just implement methods equals and hashCode.
If Set is used, can i use TreeSet, because i need to show in the asc order of id
You can if class EntityDetail implements interface Comparable<EntityDetail>. This is necessary because TreeSet must know what is the natural order of the various EntityDetail objects.
For more details please see Oracle docs on object ordering and Javadoc for Comparable
yes u can use SET instead of List in this scenario because SET will ensure that duplicate entries are eliminated. But making use of SET make sure that you have overridden "equals" and "hashcode" appropriately.
This is how you need to override equals and hashcode methods and for sorting purpose you need to implement Comparable and implement compareTo method as follows:
class EntityDetail implements Comparable<EntityDetail>{
#Override
public int hashcode(){
int result = 17;
result = 31 * result + name.hashCode();
result = 31 * result + id;
return result;
}
#Override
public boolean equals(Object o){
if (o == this) return true;
if (!(o instanceof EntityDetail)) {
return false;
}
EntityDetail ed = (EntityDetail) o;
return ed.name.equals(name) &&
ed.id == id ;
}
#Override
public int compareTo(EntityDetail ed) {
int compareId = ((EntityDetail) ed).getId();
//ascending order
return this.id - compareId;
//descending order
//return compareId - this.id;
}
}
You can use List if you can make sure in your code that the details are added in it in the order that you want. If you are not sure of the order in which you add then you can use the Collections.sort method. For this you will also want to make your OrgType implement the Comparable interface to provide a strategy to order the OrgType objects. In your case it is by id.
If you use TreeSet, the sorting is done automatically whenever you insert into the set thereby eliminating the use of Collections.sortbut you will still have to provide an ordering strategy.
Have a look at this
There are costs of using a Set because it maintains unique elements but because you have a maximum of 10 rows that won't be a problem.
I have a class Passengers which has member properties String name, int health, and String disease with setter and getter methods. The disease variable will initially hold null. Here's that class
public class Passengers
{
private String name;
private int health;
private String disease;
public Passengers(String _name, int _health, String _disease)
{
name = _name;
health = _health;
disease = _disease;
}
public void setHealth(int _health)
{
health = _health;
}
public void setDisease(String _disease)
{
disease = _disease;
}
public String getName()
{
return name;
}
public int getHealth()
{
return health;
}
public String getDisease()
{
return disease;
}
}
What I want to know is how I could add new strings onto this variable, and then how to take away. For example, a passenger Bill starts at null for his diseases, and then contracts malaria and the cold. Bill's disease variable should now hold malaria, cold. Now say the user chooses to treat Bill's malaria. How would I
1) add malaria and cold
2) subtract just malaria from disease?
Whenever I attempt to change the disease with
passengers[index].setDisease() = null;
it says "error: method setDisease in class Passengers cannot be applied to given types:
required: String
found: no arguments"
I would reccomend making disease a Set of Strings.
Set<String> diseases = new HashSet<String>();
void addDisease(String disease) {
diseases.add(disease);
}
void removeDisease(String deisease) {
diseases.remove(disease);
}
Sets are "better", in this case, than other Collections because they cannot hold duplicates.
You should give the class a List<String> such as an ArrayList<String> and put the diseases in this List.
Better still, create a class or enum of Disease and have your Passenger class use a List<Disease> and avoid over-use of String. You could then give the class public addDisease(Disease disease) and removeDisease(Disease disease) methods.
Incidentally, your class above should be named Passenger, the singular, not Passengers, the plural, since it represents the concept of a single Passenger.
For your requirement if you are using List like ArrayList you can access your elements(disease names) by index, but it will allow duplicate data to be inserted(same disease may be added multiple times, it will unnecessary increase in number of diseases and may arise some problems).
If you use Set like HashSet it will allow unique element only, so no issues related to duplicated entries but at the same time you can't access a particular disease by index (if you need so, as of now I am not aware of your further requirement).
So as best of my knowledge I suggest you to use LinkedHashSet(HashSet with Linked approach) it will provide you FIFO order without duplicate insertion problem.