I want to create a programm that creates a list that looks like this
ID: 1
Name: Example
Surname: Example
email: example
//New list
ID: 2
Name: Example
Surname: Example
email: example
and then when i want to change something (like Name: ) i'd like to change it by id, so it can only be changed inside the list with ID: 2
You should use a HashMap.
Create a class (let's class it YourClass) that contains ID, name, surname and email instance variables.
Then create a HashMap where the key is the identifier and the value is YourClass:
Map<Integer,YourClass> map = new HashMap<>();
map.put(objectOfYourClassWithID1.getID(),objectOfYourClassWithID1);
map.put(objectOfYourClassWithID2.getID(),objectOfYourClassWithID2);
if (map.containsKey(2)) {
map.get(2).setSomeProperty(newValue); // this will only change the object whose ID is 2
}
you can create class like this
public class Record{
private int id;
private String name;
private String Surname;
private String email;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return Surname;
}
public void setSurname(String surname) {
Surname = surname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
and then use it like this:
Record record1 = new Record();
record1.setId(1);
record1.setName("example");
record1.setSurname("example");
record1.setEmail("example");
Record record2 = new Record();
record2.setId(2);
record2.setName("example");
record2.setSurname("example");
record2.setEmail("example");
Map<Integer,Record> recordMap = new HashMap<Integer, Record>();
recordMap.put(record1.getId(),record1);
recordMap.put(record2.getId(),record2);]
recordMap.get(2).getName();//example
recordMap.get(2).setName("ebi");
recordMap.get(2).getName();//ebi
import java.util.ArrayList;
import java.util.List;
public class Person {
private int id;
private String name;
private String Surname;
private String email;
public Person(int id, String name, String surname, String email) {
super();
this.id = id;
this.name = name;
Surname = surname;
this.email = email;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return Surname;
}
public void setSurname(String surname) {
Surname = surname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public static void main(String[] args) {
List<Person> list = new ArrayList<Person>();
list.add(new Person(1, "example", "example", "example"));
list.add(new Person(2, "example", "example", "example"));
}
}
Related
import java.util.Date;
public class Emp {
public Emp() {
}
private int Id;
private String name;
private Date date_of_join;
private String city;
private int age;
public int getId() {
return Id;
}
public void setId(int id) {
Id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getDate_of_join() {
return date_of_join;
}
public void setDate_of_join(Date date_of_join) {
this.date_of_join = date_of_join;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
I have a bean with 5 fields. I want to sort all the five field according to 1 than 2 than 3rd than 4 and than 5
It consists of
String
String,
Date,
String ,
Int.
What could i do to sort the list<Emp> inside the list according to id, name, date of join, city, age
You create a custom Comparator:
myList.sort(Comparator.comparingInt(Emp::getId)
.thenComparing(Emp::getName)
.thenComparing(Emp::getDate_of_join)
.thenComparing(Emp::getCity)
.thenComparingInt(Emp::getAge));
EDIT:
To address the requirement in the comments, you could sort the items accoring to the length of the city's string before sorting by it:
myList.sort(Comparator.comparingInt(Emp::getId)
.thenComparing(Emp::getName)
.thenComparing(Emp::getDate_of_join)
.thenComparingInt(e -> e.getCity().length())
.thenComparing(Emp::getCity)
.thenComparingInt(Emp::getAge));
I have a List and a Map as below:
public class student {
private String name;
private String age;
private String id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
student(String id,String name,String age)
{
}
}
List<student> stulist = Arrays.asList(new student("1", "vishwa",null),
new student("3", "Ravi",null),
new student("2", "Ram",null));
Map<String,String> newmap = new HashMap() {
{
put("1","20");
put("2","30");
}
};
I am comparing like this: If id in map matches the id in list then add
age from Map to age of List.
I have tried this so far , but i am not able to get it.
newmap.entrySet().stream().filter(entry->entry.getKey().equals(student::getId)).collect(..collect here to list..);
stulist = stulist.stream().map(instance -> {
student studentInstance = instance;
studentInstance.setAge(newMap.getOrDefault(studentInstance.getId(),"<default age>"));
return studentInstance;
}).collect(Collectors.toList()); ;
ps: Use proper naming conventions. Change the class name student to Student.
Here is solution, assuming I got the question right:
import java.util.*;
import java.util.stream.*;
public class Answer {
public static void main(String[] args) {
List<Student> studentsWithoutAge = Arrays.asList(
new Student("1", "Vishwa", null),
new Student("3", "Ravi", null),
new Student("2", "Ram", null)
);
Map<String,String> ageById = new HashMap() {{
put("1","20");
put("2","30");
}};
List<Student> studentsWithAge = addAge(studentsWithoutAge, ageById);
System.out.println("Students without age: " + studentsWithoutAge);
System.out.println("Students with age: " + studentsWithAge);
}
static List<Student> addAge(List<Student> students, Map<String,String> ageById) {
return students.stream()
.map(student -> {
String age = ageById.getOrDefault(student.getId(), null);
return new Student(student.getId(), student.getName(), age);
})
.collect(Collectors.toList());
}
}
class Student {
private String name;
private String age;
private String id;
Student(String id,String name,String age){
this.id = id;
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#Override
public String toString() {
return String.format("Student: id = %s, name = %s, age = %s", this.id, this.name, this.age);
}
}
Implement Student class as #Zgurskyi comment, and then use this on main:
stulist.forEach(stu -> {
stu.setAge(newmap.getOrDefault(stu.getId(), null));
});
Use Collectors.toList()
// Accumulate names into a List
List<String> list = people.stream().map(Person::getName).collect(Collectors.toList());
I have 2 subclasses and one superclass. I try to run test file but don't work. Any suggest?
Error: https://i.imgur.com/ciG9EPF.png
First file, the superclass (persoana= person)
package proj;
public class persoana {
private String name, address, phone, email;
public persoana(){
}
public persoana(String name, String address, String phone, String email) {
this.name = name;
this.address = address;
this.phone = phone;
this.email = email;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public String getAddress(){
return address;
}
public void setAddress(String address){
this.address = address;
}
public String getPhone(){
return phone;
}
public void setPhone(String phone){
this.phone = phone;
}
public String getEmail(){
return phone;
}
public void setEmail(String email){
this.email = email;
}
}
File 2 is employee, subclass for persoana:
package proj;
public class employee extends persoana{
private String office, salary;
public employee(){
}
public employee(String office, String salary){
this.office = office;
this.salary = salary;
}
public String office(){
return office;
}
public void setOffice(String office){
this.office = office;
}
public String getSalary(){
return salary;
}
public void setSalary(String salary){
this.salary = salary;
}
}
File 3, subclass of class persoana:
package proj;
public class student extends persoana{
private String bac, adm;
public student(){
}
public student(String bac, String adm){
this.bac = bac;
this.adm = adm;
}
public String bac(){
return bac;
}
public void setBac(String bac){
this.bac = bac;
}
public String getAdm(){
return adm;
}
public void setAdm(String adm){
this.adm = adm;
}
}
And the test file where appears 2 errors at line 6 and 7
package proj;
public class test {
public static void main(String[] args) {
persoana persoana= new persoana ("John", "Somewhere", "415",
"john#somewhere.com");
persoana student= new student("Jane", "School Street", "650", "mj#abc.com");
persoana employee= new employee ("Tom ", "Street", "408", "asd");
System.out.println(persoana.toString() + "\n");
System.out.println(student.toString() + "\n");
System.out.println(employee.toString() + "\n");
}
}
Your student class don't provide that constructor (and constructor are not inherited like methods).
You need to provide it.
public student(String name, String address, String phone, String email){
super(name, adress, phone, email);
}
Note that class shoud start with a uppercase.
I am working on error handling a response mapping. Before I go ahead and map the response to my domain objects, I want to validate the response. Check for errors.
I am planning to have a Validator.java class and implement validation methods for each of the API call.
Is there any alternative way in spring to do this?
package com.people.net;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.Email;
public class UserInfo {
//Unicode check
#Pattern(regexp="[0-9a-zA-Z\\s-]+", message="chars,numbers allowed only")
String name;
int id;
#Pattern(regexp="([0-9]{10})", message="minLength=maxLength=10 only numbers")
String pin;
#Email
String email;
#Size(max=5, message="5 chars max")
String emailType;
#Size(max=5, message="5 chars max")
String addressType;
#Size(max=300, message="5 chars max")
String address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public UserInfo(String name, String pin, String id) {
super();
this.id = Integer.parseInt(id);
this.name = name;
this.pin = pin;
}
public UserInfo(int id,String name, String pin, String email, String emailType, String addressType, String address) {
super();
this.id = id;
this.name = name;
this.pin = pin;
this.email = email;
this.emailType = emailType;
this.addressType = addressType;
this.address = address;
}
public UserInfo() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPin() {
return pin;
}
public void setPin(String pin) {
this.pin = pin;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getEmailType() {
return emailType;
}
public void setEmailType(String emailType) {
this.emailType = emailType;
}
public String getAddressType() {
return addressType;
}
public void setAddressType(String addressType) {
this.addressType = addressType;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
You should explore hibernate validator which is the reference implementation JSR-349 for bean validation. more info is here https://jcp.org/en/jsr/detail?id=349 .
Also hibernate validator is a industry standard for doing the bean validation(lots of stuff available on internet) and comes with lots of popular framework like dropwizard etc.it provide annotation based validation and allow you to write your own custom annotation based validation.
please refer on step by step guide http://www.journaldev.com/2668/spring-validation-example-mvc-validator, where author uses it with the spring.
There is a compliation error stating that class name is already define i can't find the way to resolve it
further the class name are declared only once and can't find the place where the things are going wrong
package practo;
import java.io.*;
import java.lang.*;
import java.util.*;
#SuppressWarnings("unused")
class Customer /* compilation error occurs here */
{
private int id;
private String name;
private String email;
private String address;
void setid(int id)
{
this.id=id;
}
int getid()
{
return id;
}
void setname(String name)
{
this.name=name;
}
String getname()
{
return name;
}
void setemail(String email)
{
this.email=email;
}
String getemail()
{
return email;
}
void setaddress(String address)
{
this.address=address;
}
String getaddress()
{
return address;
}
class PhoneNumber
{
private String phoneNumber;
private String heldFromDate;
private String heldToDate;
void setphoneNumber(String phoneNumber)
{
this.phoneNumber=phoneNumber;
}
String getphoneNumber()
{
return phoneNumber;
}
void setheldToDate(String heldToDate)
{
this.heldToDate=heldToDate;
}
String getheldToDate()
{
return heldToDate;
}
public String getHeldFromDate() {
return heldFromDate;
}
public void setHeldFromDate(String heldFromDate) {
this.heldFromDate = heldFromDate;
}
class NumberType
{
private String code;
private String description;
void setcode(String code)
{
this.code=code;
}
void setdescription(String description)
{
this.description=description;
}
String getcode()
{
return code;
}
String getdescription()
{
return description;
}
}
}
}
class x1
{
public void main(String args[])
{
#SuppressWarnings("resource")
Scanner s=new Scanner(System.in);
Customer c=new Customer();
Customer.PhoneNumber p=c.new PhoneNumber();
Customer.PhoneNumber.NumberType n=p.new NumberType();
System.out.println("Enter the customer details");
System.out.println("Enter the id :");
int id=s.nextInt();
c.setid(id);
System.out.println(c.getid());
System.out.println("Enter the name :");
String name=s.nextLine();
c.setname(name);
System.out.println(c.getname());
System.out.println("Enter the email :");
String email=s.nextLine();
c.setemail(email);
System.out.println(c.getemail());
System.out.println("Enter the address :");
String address=s.nextLine();
c.setaddress(address);
System.out.println(c.getaddress());
System.out.println("Enter the customer contact details");
System.out.println("Enter the phone number :");
String phoneNumber=s.nextLine();
p.setphoneNumber(phoneNumber);
System.out.println(p.getphoneNumber());
System.out.println("Enter the held from date (dd/MM/yyyy) :");
String heldFromDate=s.next();
p.setHeldFromDate(heldFromDate);
System.out.println(p.getHeldFromDate());
System.out.println("Enter the held to date (dd/MM/yyyy) :");
String heldToDate=s.next();
p.setheldToDate(heldToDate);
System.out.println(p.getheldToDate());
System.out.println("Enter number type code :");
String code=s.next();
n.setcode(code);
System.out.println(n.getcode());
System.out.println("Enter number type description");
String description=s.next();
n.setdescription(description);
System.out.println(n.getdescription());
}
}
Your class does not give me any compilation error. You might try making the class public i.e. public class Customer and file name having the name Customer.java. It may happen that the package practo already contains a class named Customer.
Can you please verify Customer class is not duplicate ? If it is not there, can you choose Clean from the Project menu, it might fix these errors.
Sometime eclipse trouble us.
Lots of recommendations for improvement:
Open public class per file, and a file for each class. Your arrangement is confusing.
Learn and follow the Java coding standards.
Using a Date for a date instead of a String is a better design, especially with JDK 8 and the java.time package.
Learn JUnit instead of that x1.main.
These are examples of how your classes should look.
Customer.java
package practo;
/**
* Created by Michael
* Creation date 5/29/2016.
* #link https://stackoverflow.com/questions/37511168/it-show-the-error-that-customer-is-already-defined-please-let-me-know-whats-wron
*/
public class Customer {
private int id;
private String name;
private String email;
private String address;
public Customer() {
this(0, "", "", "");
}
public Customer(int id, String name, String email, String address) {
this.id = id;
this.name = name;
this.email = email;
this.address = address;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
PhoneNumber.java:
package practo;
/**
* Created by Michael
* Creation date 5/29/2016.
* #link https://stackoverflow.com/questions/37511168/it-show-the-error-that-customer-is-already-defined-please-let-me-know-whats-wron
*/
public class PhoneNumber {
private String phoneNumber;
private String heldFromDate; // Bad design. This ought to be a Date, not a String
private String heldToDate; // Bad design. This ought to be a Date, not a String
public PhoneNumber() {
this("", "", "");
}
public PhoneNumber(String phoneNumber, String heldFromDate, String heldToDate) {
this.phoneNumber = phoneNumber;
this.heldFromDate = heldFromDate;
this.heldToDate = heldToDate;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getHeldFromDate() {
return heldFromDate;
}
public void setHeldFromDate(String heldFromDate) {
this.heldFromDate = heldFromDate;
}
public String getHeldToDate() {
return heldToDate;
}
public void setHeldToDate(String heldToDate) {
this.heldToDate = heldToDate;
}
}
Check if you have another class called Customer in the package practo. That would cause a name conflict.