List<Employee> empListObjDeepCopy = empListRef.stream().map(inv -> new Employee(inv)).collect(Collectors.toList());
How to replace this (inv -> new Employee(inv)) lambda with Method reference.
Full Code reference:
package org.learn.copy;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class DeepCopy {
public static void main(String[] args){
Employee emp = new Employee();
emp.setName("Hello");
emp.setRollNumber("12345");
Employee emp1 = new Employee();
emp1.setName("Hi");
emp1.setRollNumber("123456");
List<Employee> empList = new ArrayList<>();
empList.add(emp);
empList.add(emp1);
List<Employee> empListRef = empList;
System.out.println("empList Obj: "+empList.get(0).getName());
System.out.println("empListRef Obj: "+empListRef.get(0).getName());
List<Employee> empListObjDeepCopy = empListRef.stream().map(inv -> new Employee(inv)).collect(Collectors.toList());
empListObjDeepCopy.get(0).setName("Hi");
System.out.println("empList Obj: "+empList.get(0).getName());
System.out.println("empListRef Obj: "+empListRef.get(0).getName());
System.out.println("empListObjDeepCopy Obj: "+empListObjDeepCopy.get(0).getName());
}
}
class Employee {
private String name;
private String rollNumber;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRollNumber() {
return rollNumber;
}
public void setRollNumber(String rollNumber) {
this.rollNumber = rollNumber;
}
public Employee(Employee employee) {
this.name = employee.name;
this.rollNumber = employee.rollNumber;
}
public Employee() {
super();
}
}
Using .map(Employee::new) is ambiguous because you have two constructors in your Employee class. Try to leave only one.
Related
I am trying to return empName if its present Or else Empty String
But i am unable to return .
After ifPresent its not allowing me to return value , please help need with the syntax .
This is my Structure
import java.util.List;
public class EmployeeData {
private List<Employee> employees = null;
public List<Employee> getEmployees() {
return employees;
}
public void setEmployees(List<Employee> employees) {
this.employees = employees;
}
}
This is my Employee class
public class Employee {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
My Test Program
import java.util.Collections;
import java.util.Optional;
public class Test {
public static void main(String args[]) {
EmployeeData empData = new EmployeeData();
}
public String getEmpName(EmployeeData empData)
{
Optional.ofNullable(empData.getEmployees()).orElseGet(Collections::emptyList)
.stream().findFirst().ifPresent(
return emp->emp.getName();
)).orElse{
return "";
}
}
}
If you want any name of one of the employees you need to map to their name, then use findFirst and orElse.
The ifPresent is to consume the data and only if their is a data : here you want to return and do something if not present
public String getEmpName(EmployeeData empData) {
return Optional.ofNullable(empData.getEmployees()).orElseGet(Collections::emptyList)
.stream().filter(Objects::nonNull)
.map(Employee::getName).findFirst().orElse("");
}
I just have this basic code where I need help adding employee data to an ArrayList of another class. I am just writing this code in preparation for an assignment, so don't bash my code too much. Essentially though, i'll be needing to add elements of employees and delete them eventually. But for now, I just need help adding the elements to my other Employee class. =]
public class main {
private static Employee employee;
public static void main(String[] args) {
employee = new Employee(10,10);
System.out.println(employee.toString());
}
}
...............
import java.util.ArrayList;
public class Employee {
public int employeeNum;
public double hourRate;
ArrayList<Employee> Employee = new ArrayList<>();
public Employee(int employeeNum, double hourRate){
this.employeeNum = employeeNum;
this.hourRate = hourRate;
}
public String toString(){
return ""+employeeNum+hourRate;
}
}
Simple Example -
package com;
import java.util.ArrayList;
public class TestPage{
public static void main(String[] args){
Employee emp1, emp2;
emp1 = new Employee();
emp2 = new Employee();
emp1.setName("MAK");
emp2.setName("MICHELE");
emp1.setAddress("NY");
emp2.setAddress("WY");
//and keep putting other information like this
ArrayList<Employee> employee = new ArrayList<Employee>();
employee.add(emp1);
employee.add(emp2);
System.out.println("emp1 name is : " + employee.get(0).getName());
System.out.println("emp2 name is : " + employee.get(1).getName());
System.out.println("emp1 address is : " + employee.get(0).getAddress());
System.out.println("emp2 address is : " + employee.get(1).getAddress());
}
}
class Employee{
String name, address;
int age, salary;
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 int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
}
It seems like what you're asking is based on one employee having sub-employees and that structurally that probably represents a hierarchy (Some commenters seem to be missing that point). But that's an assumption on my part. Based on that assumption.
A little bit of feedback to start on structure of your main class:
public class main {
public static void main(String[] args) {
Employee employee = new Employee(10,10);
System.out.println(employee.toString());
}
}
It seems to me that there's no reason to have a static instance variable for that root employee instance. You should try to limit the scope of variables where possible. It seems like it could very well be in the main() method's scope.
public class Employee {
public int employeeNum;
public double hourRate;
ArrayList<Employee> employees= new ArrayList<>();
public Employee(int employeeNum, double hourRate){
this.employeeNum = employeeNum;
this.hourRate = hourRate;
}
public String toString(){
return ""+employeeNum+hourRate;
}
public ArrayList<Employee> getEmployees() {
return this.employees;
}
}
It may be better to name your arraylist employees or employeeList. I went with employees in this case because that convention is preferable.
And in relation to your question, ArrayList is pass by reference so you could just add a getter method for the sub-employee list (employees).
To add employees from your main method you could do something like
Employee rootEmployee = new Employee(5, 10.0);
rootEmployee.getEmployees().add(new Employee(6, 5.0));
Or you could add an additional method to Employee like this:
public void addEmployee(Employee e) {
employees.add(e);
}
Hi any one give me example of ClassName.method1Name().method2Name() what is this please give me simple java program example of this.I am confusing of this code.
ClassName.get1().get2().get3() is just a chain of method calls on successive classes. Imagine 3 objects:
class ClassName {
public static o1 get1() {
return new o1();
}
}
class o1 {
public o2 get2() {
return new o2();
}
}
class o2 {
public o3 method3() {
return new o3();
}
}
In each instance, the function call returned another object, which itself had a method to call, and so on and so forth.
Return current object reference from method call using return this;
public class ReturnClassType {
private String firstname;
private String lastname;
public ReturnClassType firstName(String firstname){
this.firstname = firstname;
return this;
}
public ReturnClassType lastName(String lastname){
this.lastname = lastname;
return this;
}
public String getName(){
return firstname + " " + lastname;
}
public static void main(String[] args) {
String Name = new ReturnClassType().firstName("Vicky").lastName("Thakor").getName();
System.out.println(Name);
}
}
Class Employee{
public Static List<Employee> list=new ArrayList<Employee>();
private String name;
Employee(){
public Employee(){
name = "";
}
public String getName(){
return name;
}
public void setName(String name){
this.name=name;
}
}
public static void main(String [] args){
Employee e = new Employee();
e.setname("test");
Employee e2 = new Employee();
e2.setname("test2");
Employee.list.add(e);
Employee.list.add(e2);
for(int i = 0 ; i < Employee.list.size(); i++){
System.out.println(Employee.list.get(i).getName());
}
}
Expected Result of code is ClassCastException but Actual Result :- [Person with pid- 1 - a1-name, Person with pid- 2 - c2-name, Sorting.Employee#cdfc9c, Sorting.Employee#1837697]
Person class:
package Sorting;
public class Person implements Comparable<Person> {
private int pid;
private String pname;
public int getPid() {
return pid;
}
public void setPid(int pid) {
this.pid = pid;
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
#Override
public String toString() {
return "Person with pid- " + getPid() + " - " + getPname();
}
#Override
public int compareTo(Person p) {
return this.pid - p.pid;
}
}
Employee class:
package Sorting;
public class Employee implements Comparable {
#Override
public int compareTo(Object o) {
return 0;
}
}
SortingofObjects class:
package Sorting;
import java.util.ArrayList;
import java.util.Collections;
public class SortingofObjects {
public static void main(String[] args) {
Person p1 = new Person();
p1.setPid(1);
p1.setPname("a1-name");
Person p2 = new Person();
p2.setPid(2);
p2.setPname("c2-name");
Employee e1 = new Employee();
Employee e2 = new Employee();
ArrayList a = new ArrayList();
a.add(p1);
a.add(p2);
a.add(e1);
a.add(e2);
Collections.sort(a);
System.out.println(a);
}
}
Collections.sort does not call compareTo on every pair in the List, just enough pairs to sort the List. As an example, run this code:
public class Test implements Comparable<Test> {
public static void main(String[] args) {
List<Test> list = new ArrayList<Test>();
list.add(new Test(1));
list.add(new Test(2));
list.add(new Test(3));
list.add(new Test(4));
Collections.sort(list);
}
private final int number;
Test(int number) {
this.number = number;
}
#Override
public int compareTo(Test that) {
System.out.println(this + ".compareTo(" + that + ")");
return 0;
}
#Override
public String toString() {
return "" + number;
}
}
The output is
2.compareTo(1)
3.compareTo(2)
4.compareTo(3)
Since your List is in the order Person, Person, Employee, Employee, the only combination that would throw a ClassCastException, namely
Person.compareTo(Employee)
never occurs. If your List contained an Employee before a Person it would throw an exception.
If it just so happens that the sorting algorithm used only compares Employees to Persons, and not the other way around, then it'll never throw, because Employee.compareTo accepts any Object. You just got lucky, more or less.
I have two class in JAVA:
public class Persons implements Serializable{
String name;
String phone;
...
}
and:
public class Diary implements Comparable{
ArrayList<Persons> persons=new ArrayList();
...
}
I want to order my ArrayList by the name (in alphabetical), but I can't use Collections.sort() because my ArrayList is Persons class and this give me and error. I can't implements Comparable in class Persons because if i do it, i can't read later my ArrayList which is save in a Object .dat
try this
Collections.sort(persons, new Comparator<Persons>() {
#Override
public int compare(Persons o1, Persons o2) {
return o1.name.compareTo(o2.name);
}});
If you want a sorted collection of people I would do this.
class Dairy {
final SortedMap<String, Person> people = new TreeMap<String, Person>();
}
or
class Dairy {
final SortedSet<Person> people = new TreeSet<Person>(new MyNameComparator());
}
or
class Dairy {
final List<Person> people = new ArrayList<Person>();
public void sortPeople() {
Collections.sort(people, new MyNameComparartor());
}
}
Here is complete sample for your problem.. save below code in Test.java file and run it..
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
class Person implements Serializable{
private static final long serialVersionUID = 1L;
String name ;
String phone ;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Person(String name, String phone) {
super();
this.name = name;
this.phone = phone;
}
#Override
public String toString() {
return "Person [name=" + name + ", phone=" + phone + "]";
}
}
class Diary {
ArrayList<Person> list = new ArrayList<Person>();
public ArrayList<Person> getList() {
return list;
}
public void setList(ArrayList<Person> list) {
this.list = list;
}
public Diary(ArrayList<Person> list) {
super();
this.list = list;
}
}
public class Test
{
public static void main(String[] args) {
Person p1 = new Person("John","123");
Person p2 = new Person("Aby","456");
Person p3 = new Person("Debra","789");
ArrayList<Person> list = new ArrayList<Person>();
list.add(p1);
list.add(p2);
list.add(p3);
Diary d = new Diary(list);
Collections.sort(d.getList(), new Comparator<Person>(){
public int compare(Person item1, Person item2){
int compare = item1.getName().compareTo(item2.getName());
return compare;
}
});
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}
}
It sorts list of person in diary using comparator without touching your person class..