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..
Related
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.
I am new to java and reporting tool BIRT, I am trying to create a simple report using Pojo in Birt but I can't get it to work I create my java classes in other project and generate a jar file after that I use it to create a data source but when I try to create a data set it doesnt work, I couldn't select classes to proceed
package com.test.pojoproject;
import java.io.Serializable;
public class Person implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private int id;
private String name;
private String address;
public Person(){
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getAddress() {
return address;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setAddress(String address) {
this.address = address;
}
}
package com.test.pojoproject;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class Main implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private static List<Person> list = new ArrayList<Person>();
public static void main(String[] args) {
Main.generateData();
Main.getList();
// display created list
//list.forEach(person -> System.out.println(person.getName()));
}
public static void generateData(){
List<Person> list = new ArrayList<Person>();
for (int i = 0; i < 30; i++) {
Person person = new Person();
person.setId(i+1);
person.setName("person " + (i+1));
person.setAddress("address " + (i+1));
list.add(person);
}
Main.list = list;
}
public static List<Person> getList(){
return Main.list;
}
}
I found a solution BIRT needs to use a class withe methodes open, next and close I will post my dataset class below
package com.test.pojoproject;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class PersonDataSet {
public Iterator<Person> itr;
public List<Person> getPersons() {
List<Person> persons = new ArrayList<Person>();
for (int i = 0; i < 30; i++) {
Person person = new Person();
person.setId(i+1);
person.setName("person " + (i+1));
person.setAddress("address " + (i+1));
persons.add(person);
}
return persons;
}
public void open(Object obj, Map<String,Object> map) {
}
public Object next() {
if (itr == null)
itr = getPersons().iterator();
if (itr.hasNext())
return itr.next();
return null;
}
public void close() {
}
}
How to sort object which has two different types of object list property. both the list are type of different objects.
public class Member {
private List<Group> groups;
private List<Person> persons;
}
public class Group {
private String groupName;
}
public class Person {
private String personName;
}
Is there way to sort these two list and get combined result which will be sorted based on the name.
expected result
groupName : alex
personName : bob
groupName: christan
groupName: Dan
perosnName: Kat
Try this:
abstract class BaseClass implements Comparable{ // you could name this class as you want
protected String name;
#Override
public int compareTo(Object o) {
return this.name.compareToIgnoreCase(((BaseClass)o).name);
}
}
class Group extends BaseClass{
public Group(String name) {
this.name = name;
}
#Override
public String toString() {
return "groupName : " + name;
}
}
class Person extends BaseClass{
public Person(String name) {
this.name = name;
}
#Override
public String toString() {
return "personName : " + name;
}
}
Then to use it:
public class Main {
public static void main(String[] args) {
List<Group> groups = new ArrayList<>();
groups.add(new Group("alex"));
groups.add(new Group("christan"));
groups.add(new Group("Dan"));
List<Person> persons = new ArrayList<>();
persons.add(new Person("bob"));
persons.add(new Person("Kat"));
List<BaseClass> members = new ArrayList<>();
members.addAll(groups);
members.addAll(persons);
members.sort(BaseClass::compareTo);
members.forEach(System.out::println);
}
}
Output:
groupName : alex
personName : bob
groupName : christan
groupName : Dan
personName : Kat
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 a enum representing severity level
public enum Severity {
HIGH("H"), MEDIUM("M"), LOW("L");
}
Person one = new Person();
one.setSeverity(Severity.HIGH);
other fields ...
Person two = new Person();
two.setSeverity(Severity.LOW);
.....
Person three = new Person();
three.setSeverity(Severity.HIGH);
List<Person> persons = Lists.newArrayList();
persons.add(one);
persons.add(two);
persons.add(three);
I would like to sort persons list to sort by severity field (i.e HIGH,MEDIUM then LOW).
My expected results after sorting the persons list should be in the order of HIGH,HIGH,LOW ?
can i know how i can achieve this ?
note : I am making use of com.google.common.collect
Try below code
Create an ENUM
package com.rais;
public enum Severity {
HIGH("H"), MEDIUM("M"), LOW("L");
private final String value;
private Severity(String value) {
this.value = value;
}
}
Now Create Person class according to your requirement eg.
package com.rais;
public class Person {
private Severity severity;
private String name;
public Person(Severity severity, String name) {
super();
this.severity = severity;
this.name = name;
}
public Severity getSeverity() {
return severity;
}
public void setSeverity(Severity severity) {
this.severity = severity;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Finally create a Test Client and apply below logic.
package com.rais;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class TestClient {
public static void main(String[] args) {
Person one = new Person(Severity.HIGH, "shayam");
Person two = new Person(Severity.MEDIUM, "mohan");
Person three = new Person(Severity.LOW, "radha");
Person four = new Person(Severity.HIGH, "rakesh");
Person five = new Person(Severity.MEDIUM, "kailash");
Person six = new Person(Severity.LOW, "rais");
Person seven = new Person(Severity.LOW, "abhishek");
List<Person> persons = new ArrayList<Person>();
persons.add(one);
persons.add(two);
persons.add(three);
persons.add(four);
persons.add(five);
persons.add(six);
persons.add(seven);
Collections.sort(persons, new Comparator<Person>() {
#Override
public int compare(Person person1, Person person2) {
if(person1.getSeverity()==person2.getSeverity())
{
return person1.getName().compareTo(person2.getName());
}
else{
return person1.getSeverity().compareTo(person2.getSeverity());
}
}
});
for (Person person : persons) {
System.out.println(person.getName()+" "+ person.getSeverity());
}
}
}
I am sure you will get below output.
rakesh HIGH
shayam HIGH
kailash MEDIUM
mohan MEDIUM
abhishek LOW
radha LOW
rais LOW
Use Comparable or comparator and then apply
Collection.sort().
if using comparable interface you have to implement compareTo method and
Collection.sort(<list>)
and if using comparator then you have to override compareTo method and
Collection.sort(<list>, <comparator>)
and when to use comparatot or comparable read link:
http://iandjava.blogspot.in/2012/10/comparable-and-comparator.html
If you are using Google Collections, upgrade to Google Guava. Use its ComparisonChain class. Are you sure you want HIGH, MEDIUM, LOW in that order? The reverse fits Java comparisons better.
How do Persons have a severity level? Perhaps your class deserves a better name.
I would make Person implement Comparable, which makes the sorting code very simple and brief.
Note that enums are implicitly Comparable:
public enum Severity {
HIGH("H"), MEDIUM("M"), LOW("L");
private final String code;
private Severity(String code) {
this.code = code;
}
public String getCode() {
return code;
}
}
public class Person implements Comparable<Person> {
private Severity severity;
private final String name;
public Person(Severity severity, String name) {
this.severity = severity;
this.name = name;
}
public Severity getSeverity() {
return severity;
}
public void setSeverity(Severity severity) {
this.severity = severity;
}
public String getName() {
return name;
}
#Override
public int compareTo(Person person) {
return severity == person.severity ? name.compareTo(person.name)
: severity.compareTo(person.severity);
}
#Override
public String toString() {
return name + "(" + severity +")";
}
}
Now some test code:
Person one = new Person(Severity.HIGH, "one");
Person two = new Person(Severity.LOW, "two");
Person three = new Person(Severity.HIGH, "three");
List<Person> persons = new ArrayList<Person>();
persons.add(one);
persons.add(two);
persons.add(three);
Collections.sort(persons);
System.out.println(persons);
Output:
[one(HIGH), three(HIGH), two(LOW)]