Java 8 Optional - how to handle nested Object structures - java

Is there any simple way to reduce the lines of code to print the innermost not null object using Optional as alternative to the below code. I feels like we have to write more lines of code to avoid the null checks now.
Is there any easy way to make this code short and sweet in Java 8?
import java.util.Optional;
public class OptionalInnerStruct {
public static void main(String[] args) {
// creepy initialization step, dont worry
Employee employee = new Employee();
employee.setHuman(Optional.empty());
// with optional
Optional<Human> optionalHuman = employee.getHuman();
if (optionalHuman.isPresent()) {
Human human = optionalHuman.get();
Optional<Male> optionalMale = human.getMale();
if (optionalMale.isPresent()) {
Male male = optionalMale.get();
Optional<Integer> optionalAge = male.getAge();
if (optionalAge.isPresent()) {
System.out.println("I discovered the variable finally " + optionalAge.get());
}
}
}
// without optional in picture, it will be something like:
/*if(null! = employee.getHuman() && null!= employee.getHuman().getMale() && null! = employee.getHuman().getMale().getAge()) {
System.out.println("So easy to find variable " + employee.getHuman().getMale().getAge());
}*/
}
static class Employee {
Optional<Human> human;
public Optional<Human> getHuman() {
return human;
}
public void setHuman(Optional<Human> human) {
this.human = human;
}
}
class Human {
Optional<Male> male;
public Optional<Male> getMale() {
return male;
}
public void setMale(Optional<Male> male) {
this.male = male;
}
}
class Male {
Optional<Integer> age;
public Optional<Integer> getAge() {
return age;
}
public void setAge(Optional<Integer> age) {
this.age = age;
}
}
}

You can use Optional.flatMap here
employee.getHuman()
.flatMap(Human::getMale)
.flatMap(Male::getAge)
.ifPresent(age -> System.out.println("I discovered the variable finally " + age);

Related

Writing data from a List field to a .txt file in Java

I have just completed the following program -
//interface IFile
package zad;
public interface IFile {
void readFromFile();
}
//class Student
package zad;
public class Student implements Comparable {
private String studentName;
private int facNum, studentPoints;
public Student(int facNum, String studentName, int studentPoints) {
this.facNum = facNum;
this.studentName = studentName;
this.studentPoints = studentPoints;
}
public void setFacNum(int facNum) {
this.facNum = facNum;
}
public int getFacNum() {
return facNum;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public String getStudentName() {
return studentName;
}
public void setStudentPoints(int studentPoints) {
this.studentPoints = studentPoints;
}
public int getStudentPoints() {
return studentPoints;
}
public boolean equals(Object o) {
if(o instanceof Student && ((Student) o).getFacNum() == this.facNum) {
return true;
} else {
return false;
}
}
public String toString() {
return ("FacNum = " + facNum + ", name = " + studentName
+ ", points = " + studentPoints );
}
public int compareTo(Object o) {
return Integer.compare(this.facNum, ((Student)o).getFacNum());
}
}
//class StudentsGroup
package zad;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class StudentsGroup implements IFile, Comparable {
private String groupName;
private List<Student> studentsList = new ArrayList<Student>();
public StudentsGroup(String groupName) {
this.groupName = groupName;
}
public void printArrayList() {
for(Student o : studentsList)
System.out.println(o);
}
public int compareTo(Object o) {
if(getTotalPoints(studentsList) > getTotalPoints(((StudentsGroup)o).studentsList))
return 1;
else if(getTotalPoints(studentsList) < getTotalPoints(((StudentsGroup)o).studentsList))
return -1;
else
return 0;
}
public List getList() {
return studentsList;
}
public static int getTotalPoints(List<Student> studentsList1) {
int totalPoints = 0;
for(Student o : studentsList1) {
totalPoints += o.getStudentPoints();
}
return totalPoints;
}
public void sortByPoints() {
Collections.sort(studentsList);
}
public void readFromFile() {
Scanner sc;
try {
sc = new Scanner(new File(groupName));
while(sc.hasNext()) {
int facNum = sc.nextInt();
String studentName = sc.next();
int studentPoints = sc.nextInt();
Student object = new Student(facNum, studentName, studentPoints);
studentsList.add(object);
}
sc.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
#Override
public String toString() {
return "StudentsGroup [groupName=" + groupName + ", studentsList=" + studentsList + "]";
}
}
//class main
package zad;
import java.io.FileNotFoundException;
public class demo {
public static void main(String[] args) throws FileNotFoundException {
StudentsGroup studentsGroup1 = new StudentsGroup("D://test.txt");
StudentsGroup studentsGroup2 = new StudentsGroup("D://test2.txt");
studentsGroup1.readFromFile();
studentsGroup2.readFromFile();
studentsGroup1.printArrayList();
studentsGroup1.sortByPoints();
studentsGroup1.printArrayList();
int compareResult = studentsGroup1.compareTo(studentsGroup2);
switch(compareResult) {
case 0: System.out.println("The two lists are equal by points.");
break;
case 1: System.out.println("The first list is larger than the second.");
break;
case -1: System.out.println("The first list is smaller than the second.");
break;
}
}
}
In general, it makes an object from class StudentsGroup, reads from a file and adds to an ArrayList field, as objects of another class - Student.
How should I implement a method to write that data to a new file? Any thoughts on that?
Note: also, if possible, I would like some tips on my coding to help me write better code. Am I doing something completely wrong or unnecessary in my program? The method getTotalPoints needs to be declared as static, so that is not discussed.
UPDATE:
When I try to write the data to a file with the following code:
FileOutputStream out = new FileOutputStream("D://test3.txt");
ObjectOutputStream oout = new ObjectOutputStream(out);
for(Student o : studentsList)
oout.writeObject(o);
out.close();
oout.close();
I get an error:
Exception in thread "main" java.io.NotSerializableException: zad.Student
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at zad.StudentsGroup.writeToFile(StudentsGroup.java:80)
at zad.demo.main(demo.java:27)
Am I doing something wrong?
According to the documentation for ObjectOutputStream, the writeObject method throws a NotSerializableException because Students does not implement Serializable.
NotSerializableException - Some object to be serialized does not implement the java.io.Serializable interface.
Update your class signature to the following and implement any methods required by Serializable.
public class Student implements Comparable, Serializable
By using the ObjectOutputStream.writeObject method you have no control over the output. If you want to control how the content is actually output to the file you'll want to look into an alternative writer. Look into examples of using BufferedWriter. You could then pass Student.toString() to the writer and control the way in which the data shows up. For instance, your toString() method in Student could output field1 + "\t" + field2 + "\t" + field3 + "\t" + field4 - and you'd essentially have a tab-delimited file that you could then, for instance, import into Excel.

I have the methods, but need program code for Grade enum

I need to write a Java enumeration LetterGrade that represents letter grades A through F, including plus and minus grades.
Now this is my enumeration code:
public enum Grade {
A(true),
A_PLUS(true),
A_MINUS(true),
B(true),
B_PLUS(true),
B_MINUS(true),
C(true),
D(true),
E(true),
F(false);
final private boolean passed;
private Grade(boolean passed) {
this.passed = passed;
}
public boolean isPassing() {
return this.passed;
}
#Override
public String toString() {
final String name = name();
if (name.contains("PLUS")) {
return name.charAt(0) + "+";
}
else if (name.contains("MINUS")) {
return name.charAt(0) + "-";
}
else {
return name;
}
}
What I am confused about is writing the main program. I think it could be quite straightforward but I have no clue on how to start it.
I don't want the whole code. Just a few lines to give me a head start. The rest I will try to figure out on my own.
I imagine you have a Student class that looks like this:
class Student {
protected Grade grade = null;
public Student(Grade g) {
this.grade = g;
}
}
Then you simply add a method in this class calling the isPassing method from your enum:
public boolean isPassing() {
if (this.grade != null)
return this.grade.isPassing();
return false;
}
This is supposing the passed boolean in Grade are correctly set and are invariant.

Beginning Java Polymorphism Subclass Superclass

I am trying to practice with Polymorphism and using classes. I wrote a superclass called Card. I then wrote 3 subclasses called: IDCard, CallingCard, and DriverLicense. I then wrote another class called Billfold which is supposed to contain slots for two of the cards.
I am supposed to write a BillfoldTester program which adds two objects of different subclasses to a Billfold object.
In BillfoldTester, a DriverLicense object and a CallingCard object are instantiated and added to a Billfold, which refers to these objects with Card references.
I don't really understand how to do this. I created two Card objects but I am trying to add it to my Billfold and it wont work. I tried Billfold a = new Card (x); but it's not right... Any help is much appreciated.
public class BillfoldTester
{
public static void main (String[]args)
{
Card x= new IDCard("Julie", 1995);
Card j= new DriverLicense("Jess", 1997);
//Having trouble trying to put the objects into my Billfold and print it.
}
}
public class Billfold extends Card
{
private String card1;
private String card2;
void addCard(String Card)//Not sure if this should be String
{
card1=Card;
}
}
public class Card
{
private String name;
public Card()
//This is my superclass
{
name = "";
}
public Card(String n)
{
name = n;
}
public String getName()
{
return name;
}
public boolean isExpired()
{
return false;
}
public String format()
{
return "Card holder: " + name;
}
}
public class IDCard extends Card
{
//This is one of my subclasses
private int IDNumber;
public IDCard (String n, int id)
{
super(n);
this.IDNumber=id;
}
public String format()
{
return super.format() + IDNumber;
}
}
The polymorphism example. Not sure if the functionally is exactly what you need, but you can see the whole idea (I hope). See the showAllFormat() method of Billfold class.
The whole point is inside different format() methods of the DriverLicense and IDCard. Depending on the 'real' (or initially assigned) object the different method will be called even if you just only refer to 'Card' class.
NOTE:
You didn't provide your DriverLicense implementation, and my is just from head. I have a bit different constructor to show this sub-classes may be totally different.
import java.util.ArrayList;
import java.util.List;
class Billfold {
List<Card> list = new ArrayList<Card>(10);
void addCard(Card card) // Q: Not sure if this should be String
// A: You would like to add a Card
{
list.add(card);
}
void showAllFormat() {
// go polymorphism !...
// when you call this general 'format()' you see the subclasses
// 'format()' is executed, not from 'Card' class
for(Card x: list) {
System.out.println(x.format());
}
}
}
class Card {
private String name; /* owner */
public Card() //This is my superclass
{
name = "";
}
public Card(String n) {
name = n;
}
public String getName() {
return name;
}
public boolean isExpired() {
return false;
}
public String format() {
return "Card holder: " + name;
}
}
class IDCard extends Card {
//This is one of my subclasses
private int IDNumber;
public IDCard(String n, int id) {
super(n);
this.IDNumber = id;
}
public String format() {
return "(ID)" + super.format() + " " + IDNumber;
}
}
class DriverLicense extends Card {
private String type;
public DriverLicense(String n, String type) {
super(n);
this.type = type;
}
public String format() {
return "(DL)" + super.format() + " TYPE: " + type;
}
}
public class BillfoldTester {
public static void main(String[] args) {
Card x = new IDCard("Julie", 1995);
Card j = new DriverLicense("Jess", "AB");
Billfold bf = new Billfold();
bf.addCard(x);
bf.addCard(j);
bf.showAllFormat();
}
}
This is wrong. A Billfold is not a Card; it HAS Cards.
public class Billfold
{
List<Card> cards = new ArrayList<Card>();
void addCard(Card card) {
if (card != null) {
this.cards.add(card);
}
}
}
Prefer composition over inheritance.
You should have Billfold class have two Card objects, not two Strings:
public class Billfold
{
Card card1;
Card card2;
void addCard(Card card) {
if (card != null) {
if (card1 != null) {
this.card1 = card;
} else {
this.card2 = card;
}
}
}
Ok, you're largely on the right track, just a couple of things:
void addCard(String Card)//Not sure if this should be String
{
card1=Card;
}
You're right, this should be:
void addCard(Card card)
{
card1=card;
}
then to add them:
public class BillfoldTester
{
public static void main (String[]args)
{
Card x= new IDCard("Julie", 1995);
Card j= new DriverLicense("Jess", 1997);
Billfold bf = new Billfold();
Billfold.addCard(x);
Billfold.addCard(j);
}
}
Then add a method to Billfold to print the cards in it.
Edit: Oh yeah, and duffymo is totally right, you don't need to extends Card on Billfold

JUnit testing of java Equal method

I wrote this code but I am still new in JUnit and have no idea of testing equal and equal2 method. Below is the code I wrote. My object in this code is to see if the fname is equal to lname using equal method and by using equal2 to check if fname is same as fname(it self) maybe my code have errors too.
public class EqualMethods {
/**
* #param args
*/
private String fname;
private String lname;
public EqualMethods(String fl)
{
fname = fl;
}
public EqualMethods(String f, String l)
{
fname = f;
lname = l;
}
public String getFname() {
return fname;
}
public String getLname()
{
return lname;
}
public void setLname(String lname)
{
this.lname = lname;
}
public void setFname(String fname) {
this.fname = fname;
}
public int equal(EqualMethods name)
{
if(fname == name.getFname() && lname == name.getLname())
{
return 1;
}
else
{
return 0;
}
}
public int equal2(Object o)
{
if(o.getClass() == EqualMethods.class )
{
EqualMethods e = (EqualMethods) o;
if(this.fname.equals(e.fname))
{
return 1;
}
return 0;
}
return 0;
}
public String toString()
{
return (" My first name is: "+fname + " Last name is: " + lname);
}
The objective is to create a Junit test case to equal and equal2 as the test case i created does not provide a proper output.Here is the JUnit test case I wrote but I cant make my method static though how to get around it?
public class EqualMethodsTest extends TestCase{
#Test
public void testEqual2() {
String name = "goma";
int ret = 1;
int ans ;
ans= EqualMethods.equal2(name);
assertEquals(ret,ans);
}
}
You need to create instances of EqualMethods to compare them. Like this:
public class EqualMethodsTest extends TestCase{
#Test
public void testEqual2() {
assertEquals(1, new EqualMethods("goma").equal(new EqualMethods("goma")));
}
}
Edit:
A few comments about the code:
If you work with an actual version of junit you don't need to extend TestCase and the name of the test method does not need to start with "test".
Naming a method "equal" or "equal2" might not be the best idea ... in Object, the root of all other objects, there is already a method with the name "equals" ... might be confusing.
Most probably fname == name.getFname() does not what you want to accomplish. This compares the references to two strings, not the content. Strings are objects and are to be compared like this string1.equals(string2).
This is probably a better way to do this:
private EqualsMethods a;
private EqualsMethods b;
#Before
public void before {
a = EqualsMethods("a);
b = EqualsMethods("b);
}
#Test
public void equalTest() {
assertTrue(a.equal(b));
}
#Test
public void equal2Test() {
assertTrue(a.equal2(b));
}
I still think what your doing is a bit odd though, you should probably have two classes with the same attributes and methods - each with an equals method. Then you should created tests for both those classes. Not sure what your trying to achieve here.

Collections.sort with multiple fields

I have a list of "Report" objects with three fields (All String type)-
ReportKey
StudentNumber
School
I have a sort code goes like-
Collections.sort(reportList, new Comparator<Report>() {
#Override
public int compare(final Report record1, final Report record2) {
return (record1.getReportKey() + record1.getStudentNumber() + record1.getSchool())
.compareTo(record2.getReportKey() + record2.getStudentNumber() + record2.getSchool());
}
});
For some reason, I don't have the sorted order. One advised to put spaces in between fields, but why?
Do you see anything wrong with the code?
(originally from Ways to sort lists of objects in Java based on multiple fields)
Original working code in this gist
Using Java 8 lambda's (added April 10, 2019)
Java 8 solves this nicely by lambda's (though Guava and Apache Commons might still offer more flexibility):
Collections.sort(reportList, Comparator.comparing(Report::getReportKey)
.thenComparing(Report::getStudentNumber)
.thenComparing(Report::getSchool));
Thanks to #gaoagong's answer below.
Note that one advantage here is that the getters are evaluated lazily (eg. getSchool() is only evaluated if relevant).
Messy and convoluted: Sorting by hand
Collections.sort(pizzas, new Comparator<Pizza>() {
#Override
public int compare(Pizza p1, Pizza p2) {
int sizeCmp = p1.size.compareTo(p2.size);
if (sizeCmp != 0) {
return sizeCmp;
}
int nrOfToppingsCmp = p1.nrOfToppings.compareTo(p2.nrOfToppings);
if (nrOfToppingsCmp != 0) {
return nrOfToppingsCmp;
}
return p1.name.compareTo(p2.name);
}
});
This requires a lot of typing, maintenance and is error prone. The only advantage is that getters are only invoked when relevant.
The reflective way: Sorting with BeanComparator
ComparatorChain chain = new ComparatorChain(Arrays.asList(
new BeanComparator("size"),
new BeanComparator("nrOfToppings"),
new BeanComparator("name")));
Collections.sort(pizzas, chain);
Obviously this is more concise, but even more error prone as you lose your direct reference to the fields by using Strings instead (no typesafety, auto-refactorings). Now if a field is renamed, the compiler won’t even report a problem. Moreover, because this solution uses reflection, the sorting is much slower.
Getting there: Sorting with Google Guava’s ComparisonChain
Collections.sort(pizzas, new Comparator<Pizza>() {
#Override
public int compare(Pizza p1, Pizza p2) {
return ComparisonChain.start().compare(p1.size, p2.size).compare(p1.nrOfToppings, p2.nrOfToppings).compare(p1.name, p2.name).result();
// or in case the fields can be null:
/*
return ComparisonChain.start()
.compare(p1.size, p2.size, Ordering.natural().nullsLast())
.compare(p1.nrOfToppings, p2.nrOfToppings, Ordering.natural().nullsLast())
.compare(p1.name, p2.name, Ordering.natural().nullsLast())
.result();
*/
}
});
This is much better, but requires some boiler plate code for the most common use case: null-values should be valued less by default. For null-fields, you have to provide an extra directive to Guava what to do in that case. This is a flexible mechanism if you want to do something specific, but often you want the default case (ie. 1, a, b, z, null).
And as noted in the comments below, these getters are all evaluated immediately for each comparison.
Sorting with Apache Commons CompareToBuilder
Collections.sort(pizzas, new Comparator<Pizza>() {
#Override
public int compare(Pizza p1, Pizza p2) {
return new CompareToBuilder().append(p1.size, p2.size).append(p1.nrOfToppings, p2.nrOfToppings).append(p1.name, p2.name).toComparison();
}
});
Like Guava’s ComparisonChain, this library class sorts easily on multiple fields, but also defines default behavior for null values (ie. 1, a, b, z, null). However, you can’t specify anything else either, unless you provide your own Comparator.
Again, as noted in the comments below, these getters are all evaluated immediately for each comparison.
Thus
Ultimately it comes down to flavor and the need for flexibility (Guava’s ComparisonChain) vs. concise code (Apache’s CompareToBuilder).
Bonus method
I found a nice solution that combines multiple comparators in order of priority on CodeReview in a MultiComparator:
class MultiComparator<T> implements Comparator<T> {
private final List<Comparator<T>> comparators;
public MultiComparator(List<Comparator<? super T>> comparators) {
this.comparators = comparators;
}
public MultiComparator(Comparator<? super T>... comparators) {
this(Arrays.asList(comparators));
}
public int compare(T o1, T o2) {
for (Comparator<T> c : comparators) {
int result = c.compare(o1, o2);
if (result != 0) {
return result;
}
}
return 0;
}
public static <T> void sort(List<T> list, Comparator<? super T>... comparators) {
Collections.sort(list, new MultiComparator<T>(comparators));
}
}
Ofcourse Apache Commons Collections has a util for this already:
ComparatorUtils.chainedComparator(comparatorCollection)
Collections.sort(list, ComparatorUtils.chainedComparator(comparators));
Do you see anything wrong with the code?
Yes. Why are you adding the three fields together before you compare them?
I would probably do something like this: (assuming the fields are in the order you wish to sort them in)
#Override public int compare(final Report record1, final Report record2) {
int c;
c = record1.getReportKey().compareTo(record2.getReportKey());
if (c == 0)
c = record1.getStudentNumber().compareTo(record2.getStudentNumber());
if (c == 0)
c = record1.getSchool().compareTo(record2.getSchool());
return c;
}
I'd make a comparator using Guava's ComparisonChain:
public class ReportComparator implements Comparator<Report> {
public int compare(Report r1, Report r2) {
return ComparisonChain.start()
.compare(r1.getReportKey(), r2.getReportKey())
.compare(r1.getStudentNumber(), r2.getStudentNumber())
.compare(r1.getSchool(), r2.getSchool())
.result();
}
}
This is an old question so I don't see a Java 8 equivalent. Here is an example for this specific case.
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* Compares multiple parts of the Report object.
*/
public class SimpleJava8ComparatorClass {
public static void main(String[] args) {
List<Report> reportList = new ArrayList<>();
reportList.add(new Report("reportKey2", "studentNumber2", "school1"));
reportList.add(new Report("reportKey4", "studentNumber4", "school6"));
reportList.add(new Report("reportKey1", "studentNumber1", "school1"));
reportList.add(new Report("reportKey3", "studentNumber2", "school4"));
reportList.add(new Report("reportKey2", "studentNumber2", "school3"));
System.out.println("pre-sorting");
System.out.println(reportList);
System.out.println();
Collections.sort(reportList, Comparator.comparing(Report::getReportKey)
.thenComparing(Report::getStudentNumber)
.thenComparing(Report::getSchool));
System.out.println("post-sorting");
System.out.println(reportList);
}
private static class Report {
private String reportKey;
private String studentNumber;
private String school;
public Report(String reportKey, String studentNumber, String school) {
this.reportKey = reportKey;
this.studentNumber = studentNumber;
this.school = school;
}
public String getReportKey() {
return reportKey;
}
public void setReportKey(String reportKey) {
this.reportKey = reportKey;
}
public String getStudentNumber() {
return studentNumber;
}
public void setStudentNumber(String studentNumber) {
this.studentNumber = studentNumber;
}
public String getSchool() {
return school;
}
public void setSchool(String school) {
this.school = school;
}
#Override
public String toString() {
return "Report{" +
"reportKey='" + reportKey + '\'' +
", studentNumber='" + studentNumber + '\'' +
", school='" + school + '\'' +
'}';
}
}
}
If you want to sort by report key, then student number, then school, you should do something like this:
public class ReportComparator implements Comparator<Report>
{
public int compare(Report r1, Report r2)
{
int result = r1.getReportKey().compareTo(r2.getReportKey());
if (result != 0)
{
return result;
}
result = r1.getStudentNumber().compareTo(r2.getStudentNumber());
if (result != 0)
{
return result;
}
return r1.getSchool().compareTo(r2.getSchool());
}
}
This assumes none of the values can be null, of course - it gets more complicated if you need to allow for null values for the report, report key, student number or school.
While you could get the string concatenation version to work using spaces, it would still fail in strange cases if you had odd data which itself included spaces etc. The above code is the logical code you want... compare by report key first, then only bother with the student number if the report keys are the same, etc.
I suggest to use Java 8 Lambda approach:
List<Report> reportList = new ArrayList<Report>();
reportList.sort(Comparator.comparing(Report::getRecord1).thenComparing(Report::getRecord2));
Sorting with multiple fields in Java8
package com.java8.chapter1;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import static java.util.Comparator.*;
public class Example1 {
public static void main(String[] args) {
List<Employee> empList = getEmpList();
// Before Java 8
empList.sort(new Comparator<Employee>() {
#Override
public int compare(Employee o1, Employee o2) {
int res = o1.getDesignation().compareTo(o2.getDesignation());
if (res == 0) {
return o1.getSalary() > o2.getSalary() ? 1 : o1.getSalary() < o2.getSalary() ? -1 : 0;
} else {
return res;
}
}
});
for (Employee emp : empList) {
System.out.println(emp);
}
System.out.println("---------------------------------------------------------------------------");
// In Java 8
empList.sort(comparing(Employee::getDesignation).thenComparing(Employee::getSalary));
empList.stream().forEach(System.out::println);
}
private static List<Employee> getEmpList() {
return Arrays.asList(new Employee("Lakshman A", "Consultent", 450000),
new Employee("Chaitra S", "Developer", 250000), new Employee("Manoj PVN", "Developer", 250000),
new Employee("Ramesh R", "Developer", 280000), new Employee("Suresh S", "Developer", 270000),
new Employee("Jaishree", "Opearations HR", 350000));
}
}
class Employee {
private String fullName;
private String designation;
private double salary;
public Employee(String fullName, String designation, double salary) {
super();
this.fullName = fullName;
this.designation = designation;
this.salary = salary;
}
public String getFullName() {
return fullName;
}
public String getDesignation() {
return designation;
}
public double getSalary() {
return salary;
}
#Override
public String toString() {
return "Employee [fullName=" + fullName + ", designation=" + designation + ", salary=" + salary + "]";
}
}
If the StudentNumber is numeric it will not be sorted numeric but alphanumeric.
Do not expect
"2" < "11"
it will be:
"11" < "2"
Use Comparator interface with methods introduced in JDK1.8: comparing and thenComparing, or more concrete methods: comparingXXX and thenComparingXXX.
For example, if we wanna sort a list of persons by their id firstly, then age, then name:
Comparator<Person> comparator = Comparator.comparingLong(Person::getId)
.thenComparingInt(Person::getAge)
.thenComparing(Person::getName);
personList.sort(comparator);
If you want to sort based on ReportKey first then Student Number then School, you need to compare each String instead of concatenating them. Your method might work if you pad the strings with spaces so that each ReportKey is the same length and so on, but it is not really worth the effort. Instead just change the compare method to compare the ReportKeys, if compareTo returns 0 then try StudentNumber, then School.
I had the same issue and I needed an algorithm using a config file. In This way you can use multiple fields define by a configuration file (simulate just by a List<String) config)
public static void test() {
// Associate your configName with your Comparator
Map<String, Comparator<DocumentDto>> map = new HashMap<>();
map.put("id", new IdSort());
map.put("createUser", new DocumentUserSort());
map.put("documentType", new DocumentTypeSort());
/**
In your config.yml file, you'll have something like
sortlist:
- documentType
- createUser
- id
*/
List<String> config = new ArrayList<>();
config.add("documentType");
config.add("createUser");
config.add("id");
List<Comparator<DocumentDto>> sorts = new ArrayList<>();
for (String comparator : config) {
sorts.add(map.get(comparator));
}
// Begin creation of the list
DocumentDto d1 = new DocumentDto();
d1.setDocumentType(new DocumentTypeDto());
d1.getDocumentType().setCode("A");
d1.setId(1);
d1.setCreateUser("Djory");
DocumentDto d2 = new DocumentDto();
d2.setDocumentType(new DocumentTypeDto());
d2.getDocumentType().setCode("A");
d2.setId(2);
d2.setCreateUser("Alex");
DocumentDto d3 = new DocumentDto();
d3.setDocumentType(new DocumentTypeDto());
d3.getDocumentType().setCode("A");
d3.setId(3);
d3.setCreateUser("Djory");
DocumentDto d4 = new DocumentDto();
d4.setDocumentType(new DocumentTypeDto());
d4.getDocumentType().setCode("A");
d4.setId(4);
d4.setCreateUser("Alex");
DocumentDto d5 = new DocumentDto();
d5.setDocumentType(new DocumentTypeDto());
d5.getDocumentType().setCode("D");
d5.setId(5);
d5.setCreateUser("Djory");
DocumentDto d6 = new DocumentDto();
d6.setDocumentType(new DocumentTypeDto());
d6.getDocumentType().setCode("B");
d6.setId(6);
d6.setCreateUser("Alex");
DocumentDto d7 = new DocumentDto();
d7.setDocumentType(new DocumentTypeDto());
d7.getDocumentType().setCode("B");
d7.setId(7);
d7.setCreateUser("Alex");
List<DocumentDto> documents = new ArrayList<>();
documents.add(d1);
documents.add(d2);
documents.add(d3);
documents.add(d4);
documents.add(d5);
documents.add(d6);
documents.add(d7);
// End creation of the list
// The Sort
Stream<DocumentDto> docStream = documents.stream();
// we need to reverse this list in order to sort by documentType first because stream are pull-based, last sorted() will have the priority
Collections.reverse(sorts);
for(Comparator<DocumentDto> entitySort : sorts){
docStream = docStream.sorted(entitySort);
}
documents = docStream.collect(Collectors.toList());
// documents has been sorted has you configured
// in case of equality second sort will be used.
System.out.println(documents);
}
Comparator objects are really simple.
public class IdSort implements Comparator<DocumentDto> {
#Override
public int compare(DocumentDto o1, DocumentDto o2) {
return o1.getId().compareTo(o2.getId());
}
}
public class DocumentUserSort implements Comparator<DocumentDto> {
#Override
public int compare(DocumentDto o1, DocumentDto o2) {
return o1.getCreateUser().compareTo(o2.getCreateUser());
}
}
public class DocumentTypeSort implements Comparator<DocumentDto> {
#Override
public int compare(DocumentDto o1, DocumentDto o2) {
return o1.getDocumentType().getCode().compareTo(o2.getDocumentType().getCode());
}
}
Conclusion : this method isn't has efficient but you can create generic sort using a file configuration in this way.
Here is a full example comparing 2 fields in an object, one String and one int, also using Collator to sort.
public class Test {
public static void main(String[] args) {
Collator myCollator;
myCollator = Collator.getInstance(Locale.US);
List<Item> items = new ArrayList<Item>();
items.add(new Item("costrels", 1039737, ""));
items.add(new Item("Costs", 1570019, ""));
items.add(new Item("costs", 310831, ""));
items.add(new Item("costs", 310832, ""));
Collections.sort(items, new Comparator<Item>() {
#Override
public int compare(final Item record1, final Item record2) {
int c;
//c = record1.item1.compareTo(record2.item1); //optional comparison without Collator
c = myCollator.compare(record1.item1, record2.item1);
if (c == 0)
{
return record1.item2 < record2.item2 ? -1
: record1.item2 > record2.item2 ? 1
: 0;
}
return c;
}
});
for (Item item : items)
{
System.out.println(item.item1);
System.out.println(item.item2);
}
}
public static class Item
{
public String item1;
public int item2;
public String item3;
public Item(String item1, int item2, String item3)
{
this.item1 = item1;
this.item2 = item2;
this.item3 = item3;
}
}
}
Output:
costrels
1039737
costs
310831
costs
310832
Costs
1570019
A lot of answers above have fields compared in single comparator method which is not actually working. There are some answers though with different comparators implemented for each field, I am posting this because this example would be much more clearer and simple to understand I am believing.
class Student{
Integer bornYear;
Integer bornMonth;
Integer bornDay;
public Student(int bornYear, int bornMonth, int bornDay) {
this.bornYear = bornYear;
this.bornMonth = bornMonth;
this.bornDay = bornDay;
}
public Student(int bornYear, int bornMonth) {
this.bornYear = bornYear;
this.bornMonth = bornMonth;
}
public Student(int bornYear) {
this.bornYear = bornYear;
}
public Integer getBornYear() {
return bornYear;
}
public void setBornYear(int bornYear) {
this.bornYear = bornYear;
}
public Integer getBornMonth() {
return bornMonth;
}
public void setBornMonth(int bornMonth) {
this.bornMonth = bornMonth;
}
public Integer getBornDay() {
return bornDay;
}
public void setBornDay(int bornDay) {
this.bornDay = bornDay;
}
#Override
public String toString() {
return "Student [bornYear=" + bornYear + ", bornMonth=" + bornMonth + ", bornDay=" + bornDay + "]";
}
}
class TestClass
{
// Comparator problem in JAVA for sorting objects based on multiple fields
public static void main(String[] args)
{
int N,c;// Number of threads
Student s1=new Student(2018,12);
Student s2=new Student(2018,12);
Student s3=new Student(2018,11);
Student s4=new Student(2017,6);
Student s5=new Student(2017,4);
Student s6=new Student(2016,8);
Student s7=new Student(2018);
Student s8=new Student(2017,8);
Student s9=new Student(2017,2);
Student s10=new Student(2017,9);
List<Student> studentList=new ArrayList<>();
studentList.add(s1);
studentList.add(s2);
studentList.add(s3);
studentList.add(s4);
studentList.add(s5);
studentList.add(s6);
studentList.add(s7);
studentList.add(s8);
studentList.add(s9);
studentList.add(s10);
Comparator<Student> byMonth=new Comparator<Student>() {
#Override
public int compare(Student st1,Student st2) {
if(st1.getBornMonth()!=null && st2.getBornMonth()!=null) {
return st2.getBornMonth()-st1.getBornMonth();
}
else if(st1.getBornMonth()!=null) {
return 1;
}
else {
return -1;
}
}};
Collections.sort(studentList, new Comparator<Student>() {
#Override
public int compare(Student st1,Student st2) {
return st2.getBornYear()-st1.getBornYear();
}}.thenComparing(byMonth));
System.out.println("The sorted students list in descending is"+Arrays.deepToString(studentList.toArray()));
}
}
OUTPUT
The sorted students list in descending is[Student [bornYear=2018, bornMonth=null, bornDay=null], Student [bornYear=2018, bornMonth=12, bornDay=null], Student [bornYear=2018, bornMonth=12, bornDay=null], Student [bornYear=2018, bornMonth=11, bornDay=null], Student [bornYear=2017, bornMonth=9, bornDay=null], Student [bornYear=2017, bornMonth=8, bornDay=null], Student [bornYear=2017, bornMonth=6, bornDay=null], Student [bornYear=2017, bornMonth=4, bornDay=null], Student [bornYear=2017, bornMonth=2, bornDay=null], Student [bornYear=2016, bornMonth=8, bornDay=null]]
im my case List of Lists (in the approximation examle):
List<T>.steam
.map(Class1.StaticInnerClass1::Field1)
.flatMap(x -> x.getField11ListStaticInnerClass2OfField1.stream())
.max(Comparator.comparing(Class1.StaticInnerClass2::Field21,Collections.reverseOrder())
.thenCompare(Class1.StaticInnerClass2::Field22));
For my case, I had 3 fields (For example - int index, bool isArchive ,bool isClassPrivate)
and I summed their comparison result like this-
Collections.sort(getData(), (o1, o2) ->
Integer.compare(o1.getIndex(getContext()), o2.getIndex(getContext()))
+ Boolean.compare(o1.isArchive(), o2.isArchive())
+ Boolean.compare(o1.isClassPrivate(), o2.isClassPrivate()
));

Categories