Java, compare Strings in a list of object.s - java

Hello and sorry if I did not explain myself properly.
I am trying to compare if a String is within a previously created list of objects.
example:
List<People> listOfPeople = new ArrayList<>();
Person person1 = new Person("Marija" , "Zagreb");
Person person2 = new Person("Joan", "Barcelona");
Person person3 = new Person("Vinko" , "Zagreb");
listOfPeople.add(person1);
listOfPeople.add(person2);
listOfPeople.add(person3);
What I want to do is checking the city value and be able to create a message if a person appears has the same location. I can't seem to search strings of specific values within a list.
listOfPeople.contains is telling me "given object cannot contain instances of String.
Please let me know if I should extend my question.
Thanks beforehand.

From java8, you can use stream, example bellow
import java.util.ArrayList;
import java.util.List;
public class newExample {
public static void main(String[] args) {
List<People> listOfPeople = new ArrayList<People>();
People People1 = new People("Marija", "Zagreb");
People People2 = new People("Joan", "Barcelona");
People People3 = new People("Vinko", "Zagreb");
listOfPeople.add(People1);
listOfPeople.add(People2);
listOfPeople.add(People3);
String city = "Barcelona";
if (listOfPeople.stream().anyMatch(x -> x.getCity().equals(city))) {
// found
}
}
}
class People {
String name;
String city;
public People(String name, String city) {
this.name = name;
this.city = city;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}

Assuming you are using Java 8 and above, you can use this:
package com.Example;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Person> listOfPeople = new ArrayList<>();
Person person1 = new Person("Marija" , "Zagreb");
Person person2 = new Person("Joan", "Barcelona");
Person person3 = new Person("Vinko" , "Zagreb");
listOfPeople.add(person1);
listOfPeople.add(person2);
listOfPeople.add(person3);
listOfPeople.stream()
.filter(p -> p.getCity().equals("Barcelona"))
.forEach(System.out::println);
}
}
class Person implements Serializable{
private static final long serialVersionUID = -414171236169806542L;
private String name;
private String city;
public Person(String name, String city) {
super();
this.name = name;
this.city = city;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
#Override
public String toString() {
return "Person [name=" + name + ", city=" + city + "]";
}
}
Output:
Person [name=Joan, city=Barcelona]

Related

What is my java code missing - won't output anything

When I run my code in NetBeans, it just says Build Successful, it does not include any output.
Can you please help me review my code to find out what it is missing?
I have tried everything that I know to do.
public class Lab04 {
public static void main(String[] args) {
class Person {
String name;
String address;
String phoneNumber;
public Person(String name, String address, String phoneNumber) {
this.name = name;
this.address = address;
this.phoneNumber = phoneNumber;
}
#Override
public String toString() {
return String.format("Name: "+name+"Address: "+address+"Phone Number: "+phoneNumber);
}
public static class Student extends Person {
String status;
public Student(String name, String address, String phoneNumber, String status) {
super(name, address, phoneNumber);
this.status = status;
}
#Override
public String toString() {
return String.format("Name: "+name+"Address: "+address+"Phone Number: "+phoneNumber+"Status: "+status);
}
}
public static class Instructor extends Person {
String rank;
public Instructor(String name, String address, String phoneNumber, String rank) {
super(name,address,phoneNumber);
this.rank = rank;
}
#Override
public String toString() {
return String.format("Name: "+name+"Address: "+address+"Phone Number: "+phoneNumber+"Rank: "+rank);
}
}
//Testing code - printing statements
public class TestingCode {
public static void main(String [] args) {
Person person = new Person("Peter", "111 Main St.", "2223333");
System.out.println(person);
person = new Student("Susan", "123 2nd Ave.", "3334444", "Sophomore");
System.out.println(person);
person = new Instructor("Frank", "4315 Walnut Ct.", "4445555", "Professor");
System.out.println(person);
}
}
}
}
}
Click the link for the assignment description
I made some changes to your code the main mistake was while using inheritance try to use different files so that readability of code increases.
Whenever a child class extends a parent class make sure to completely close the parent class and then start the child else it leads to error.
Also there is no need to override toString() method each time instead you can just create a display method in the parent class and make the extra variables in the child classes private so that they can be accessed using getters and setters.
Main Class:
class Person {
public String name;
public String address;
public String phoneNumber;
public Person(String name, String address, String phoneNumber) {
this.name = name;
this.address = address;
this.phoneNumber = phoneNumber;
}
public void displayDetails() {
System.out.println("name is "+ this.name);
System.out.println("address is "+ this.address);
System.out.println("Phone number is "+this.phoneNumber);
}
}
class Student extends Person {
private String status;//made this private so that you can access using getters and setters
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Student(String name, String address, String phoneNumber, String status) {
super(name, address, phoneNumber);
this.status = status;
}
}
class Instructor extends Person {
private String rank;//made this private so that you can access using getters and setters
public Instructor(String name, String address, String phoneNumber, String rank) {
super(name,address,phoneNumber);
this.rank = rank;
}
public String getRank() {
return rank;
}
public void setRank(String rank) {
this.rank = rank;
}
}
Tester Class:(make sure to create this in a seperate file)
public class TestingCode {
public static void main(String [] args) {
Person person = new Person("a","b","c");
person.displayDetails();
System.out.println("-------------\n");
Student y = new Student("Susan", "123 2nd Ave.", "3334444", "Sophomore");
y.displayDetails();
System.out.println(y.getStatus());
System.out.println("-------------\n");
Person y1= new Student("Frank", "4315 Walnut Ct.", "4445555", "Sophomore");//dynamic binding from parent to child
y1.displayDetails();
System.out.println("-------------\n");
Instructor y2= new Instructor("Frank", "4315 Walnut Ct.", "4445555", "Professor");
y2.displayDetails();
System.out.println(y2.getRank());
}
}

Best way to handle mutable fields while making a class Immutable

I want to make Footballer class immutable, it has Address field which is mutable, so what is the best way to make it immutable,
Typically for HomeAddress and Area,I can use
Clone
Serialization
Copy Constructor
Since clone is broken,How to chose between copy constructor or Serialization.
package com.javaeight;
import java.util.ArrayList;
import java.util.List;
public class ImmutableDemo {
public static void main(String[] args) {
String name = "ronaldo";
int age = 27;
List<String> clubs = new ArrayList<>();
clubs.add("MU");
clubs.add("BC");
Area area = new Area(22, 11);
HomeAddress address = new HomeAddress("Bangalore", "India", area);
Footballer footballer = new Footballer(name, age, clubs, address);
}
}
final class Footballer {
private final String name;
private final int age;
private final List<String> clubs;
private final HomeAddress address;
public Footballer(String name, int age, List<String> clubs, HomeAddress homeAddress) {
this.name = name;
this.age = age;
this.clubs = new ArrayList<>(clubs);
this.address = new HomeAddress(homeAddress.getCity(), homeAddress.getCountry(), homeAddress.getArea());
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public List<String> getClubs() {
return new ArrayList<>(clubs);
}
#Override
public String toString() {
return "Footballer{" +
"name='" + name + '\'' +
", age=" + age +
", clubs=" + clubs +
'}';
}
}
class HomeAddress {
private String city;
private String country;
private Area area;
public HomeAddress(String city, String country, Area area) {
this.city = city;
this.country = country;
this.area = area;
}
public String getCity() {
return city;
}
public String getCountry() {
return country;
}
public Area getArea() {
return area;
}
}
class Area {
private int Street;
private int buildingNumber;
public Area(int street, int buildingNumber) {
Street = street;
this.buildingNumber = buildingNumber;
}
public int getStreet() {
return Street;
}
public int getBuildingNumber() {
return buildingNumber;
}
}

Convert model to List<Object> of fields

I would like to find an efficient way of converting any object to the List<Object> of it's fields so for example:
public class User {
private String name; // John
private String surname; // Wick
private int age; // 55
}
would end up as List with the next elements: {"John", "Wick", 55}.
I know I can do it using reflection but are there any ObjectUtils or ReflectionUtils methods that are already doing that?
I did a method that should help you. Your class must contain a "getter" for each attribute. Ex:
name -> getName();
Online example
User.java
import java.lang.String;
public class User {
private String name;
private String surname;
private int age;
public User(){
this.name = "John";
this.surname = "Wick";
this.age =55;
}
public String getName(){
return this.name;
}
public String getSurname(){
return this.surname;
}
public int getAge(){
return this.age;
}
}
Main.java
import java.util.List;
class Main {
public static void main(String[] args) {
User u = new User();
List<Object> list = ReflexionUtils.getListOfFields(u);
for(Object o : list){
System.out.println(o);
}
}
}
ReflexionUtils.java
import java.lang.reflect.Field;
import java.util.List;
import java.lang.String;
import java.util.ArrayList;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class ReflexionUtils {
public static List<Object> getListOfFields(Object bean){
List<Object> result = new ArrayList<Object>();
for (Field f : bean.getClass().getDeclaredFields()) {
try{
String name = f.getName();
name = name.substring(0,1).toUpperCase() + name.substring(1);
Method m = bean.getClass().getDeclaredMethod("get"+name, null);
Object o = m.invoke(bean, null);
result.add(o);
} catch (Exception e){
System.out.println(e.getMessage());
}
}
return result;
}
}
For simplicity, override toString() method of User class and then convert it to List<Object>.
public class User {
private String name; // John
private String surname; // Wick
private int age; // 55
public User(String name, String surname, int age) {
this.name = name;
this.surname = surname;
this.age = age;
}
public String getName() {
return name;
}
public String getSurname() {
return surname;
}
public int getAge() {
return age;
}
#Override
public String toString() {
return ""+getName()+ ", "+getSurname()+", "+getAge()+"";
}
}
Then convert:
User a = new User("John","Wick",55);
List<Object> items = Arrays.asList(a.toString().split("\\s*,\\s*"));
It gives output like this:
[John, Wick, 55]

Serialization of Object to XML using Jackson [duplicate]

This question already has answers here:
Serialize Java List to XML using Jackson XML mapper
(3 answers)
Closed 5 years ago.
I am learning to use Jackson to serialize XML. My class structure is as below.
class City {
#JacksonXmlProperty(localName = "CityName")
String cityName;
public City(String cityName) {
this.cityName = cityName;
}
public String getcityName() {
return cityName;
}
public void setcity(String cityName) {
this.cityName = cityName;
}
}
#JacksonXmlRootElement(localName = "Person")
class Person {
#JacksonXmlProperty(localName = "name")
private String name;
#JacksonXmlProperty(localName = "age")
private String age;
#JacksonXmlProperty(localName = "city")
private List<City> city;
public Person() { }
Person(String name, String age, List<City> city) {
this.name = name;
this.age = age;
this.city = city;
}
public String getname() {
return name;
}
public String getage() {
return age;
}
public List<City> getcity() {
return city;
}
public void setname(String name) {
this.name = name;
}
public void setage(String age) {
this.age = age;
}
public void setcity(List<City> city) {
this.city = city;
}
}
When I try to serialize a class to XML using Jackson, I get two tags for <city>
public class App
{
public static void main( String[] args )
{
try {
XmlMapper xmlMapper2 = new XmlMapper();
Person p = new Person();
City c1 = new City("abc");
City c2 = new City("def");
City c3 = new City("ghi");
List<City> cityList = new ArrayList<City>();
cityList.add(c1);
cityList.add(c2);
cityList.add(c3);
p.setname("setattr");
p.setage("55");
p.setcity(cityList);
xmlMapper2.enable(SerializationFeature.INDENT_OUTPUT);
String respPerson = xmlMapper2.writeValueAsString(p);
System.out.println(respPerson);
} catch (Exception e) {
e.printStackTrace();
}
}
This is the output that I get.
<Person><name>setattr</name><age>55</age><city><city><CityName>sfo</CityName></city><city><CityName>sjc</CityName></city><city><CityName>sea</CityName></city></city></Person>
Can you help me to understand why do I get two tags for city and how I can fix it?
I would like the output to be something like,
<Person><name>setattr</name><age>55</age><city><CityName>sfo</CityName><CityName>sjc</CityName><CityName>sea</CityName></city></Person>
You have a list of cities. Jackson is using 'city' for both the list itself and the members of the list. If you change the local name to 'cities', you might like the results better.
Unfortunately, this isn't the right answer. It appears, rather, that the right answer is provided https://stackoverflow.com/a/27144625/131433.

Deserialize yaml to list of objects

Say I have a Yaml file like this,
people:
- name : Joe
surname : Barber
age : 16
- name : Andy
surname : Lots
age : 17
And I have a class like this,
public class people {
private String name;
private String surname;
private String age;
<!-- With getters and setters -->
}
How would i go about getting a list of people objects from the Yaml file?
Just getting the value from a key in the file is fairly simple but mapping it to a collection of objects is not.
I am using the snakeYaml lib.
i hope this can help you.
public class StackOverflow {
public static void main(String[] args) {
final URL resource = StackOverflow.class.getResource("people.yaml");
final Constructor peopleContructor = new Constructor(Group.class);
final TypeDescription peopleDescription = new TypeDescription(People.class);
peopleDescription.putMapPropertyType("people", People.class, Object.class);
peopleContructor.addTypeDescription(peopleDescription);
final Yaml yaml = new Yaml(peopleContructor);
try {
final Group group = (Group) yaml.load(resource.openStream());
for (final People people : group.getPeople()) {
System.out.println(people);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static class People {
private String name;
private String surname;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
#Override
public String toString() {
return "People: {name: " + this.name + ", surname: " + this.surname + ", age: " + this.age + "}";
}
}
public static class Group {
private List<People> people;
public List<People> getPeople() {
return people;
}
public void setPeople(List<People> people) {
this.people = people;
}
}}

Categories