How to replace < & > to string - java

What can I replace the < and > with because i want to compare string below one is compare int, so got any solution to solve this question and doesnt change the function.
public int compareTo(Object o) {
Patient p = (Patient) o;
if (this.getCategory() < p.getCategory())
return -1;
if (this.getCategory() > p.getCategory())
return 1;
else {
if (this.getTimeArrived().before(p.getTimeArrived()))
return -1;
if (this.getTimeArrived().after(p.getTimeArrived()))
return 1;
}
return 0;
}
How about this? can change the > & < to another solution because i want to compare with string
import java.util.Comparator;
public class PatientComparator implements Comparator<Patient>{
public int compare(Patient p1, Patient p2) {
if (p1.getCategory() < p2.getCategory())
return -1;
if (p1.getCategory() > p2.getCategory())
return 1;
else { if (p1.getTimeArrived().before(p2.getTimeArrived()))
return -1;
if (p1.getTimeArrived().after(p2.getTimeArrived()))
return 1;
}
return 0;
}
}

From the additional information you provided (currently inside an answer) getCategory() returns a String and getTimeArrived() returns a java.util.Date. Your goal seems to be: Compare by "category" and, if equal, then compare by "time arrived".
Both String and Date implement the Comparable interface, so you can do something like this:
public int compareTo(Patient other) {
// This code doesn't handle nulls
int result = getCategory().compareTo(other.getCategory());
if (result == 0) {
result = getTimeArrived().compareTo(other.getTimeArrived());
}
return result;
}
You could also create a Comparator.
Comparator<Patient> c = Comparator.comparing(Patient::getCategory)
.thenComparing(Patient::getArrivedTime);
Also, you are creating a compareTo method without Patient implementing Comparable. You should change it to:
public class Patient implements Comparable<Patient> { /* code */ }
Then override the compareTo method declared in Comparable. This also forces you to use compareTo(Patient) rather than compareTo(Object).

Related

Ordering the results of an file with ArrayList and compareTo

I have to order an arrayList that contains lines from a file by account ID and then by salary to get this result:
CuentaAhorro : 11111111A (Alicia) Saldo 111,11
CuentaAhorro : 12345678A (Lucas) Saldo 5100,00
CuentaCorriente: 22222222B (Peio) Saldo 222,22
CuentaAhorro : 33333333C (Isabel) Saldo 4433,33
CuentaCorriente: 33333333C (Isabel) Saldo 3333,33
CuentaAhorro : 87654321A (Asier) Saldo 3000,00
My arrayList calls the compareTo method from Bank.java.
public void ordenarCuentas() {
Collections.sort(cuentas);
}
The call is to the method compareTo in an abstract class called Account with the comparable interface:
#Override
public int compareTo(Cuenta unaCuenta) {
Cliente unTitular = unaCuenta.titular;
if(unTitular.toString().equals(unaCuenta.titular.toString()) == true) {
return 0;
// if(saldo < unaCuenta.saldo) {
// return -1;
// } else if (saldo > unaCuenta.saldo) {
// return 1;
// } else {
// return 0;
// }
}
return -1;
}
I need to check if the object 'Cuenta unaCuenta' passed as a parameter has the same account number as another and then sort by the amount of money in the account, however I am not sure how to get the condition right, as you can see, with the commented if I get the salary in the right descending order but not the account IDs.
The object Cuenta unaCuenta contains titular which contains account number and name.
The object Cliente unTitular contains the account number and name.
Could somebody lend me a hand please?
I am not able understand it very clearly because of language barrier
But if you have a arraylist you can call sort method on it an pass a comparator to get the desired sorting , something like below.
It is just to give you an idea
ArrayList<String> list = new ArrayList<>();
list.sort(new Comparator() {
#Override
public int compare(Object o1, Object o2) {
if(o1.account.equals(o2.account)) return 0;
return o1.amount - o2.amount;
}
});
as Lambda
ArrayList<String> list = new ArrayList<>();
list.sort((o1,o2) ->
if(o1.account.equals(o2.account)) return 0;
return o1.amount - o2.amount;
});
Thank you everyone for the comments. Next time i'll translate the Spanish code to English. I'll post my solution incase someone comes across this question.
(in my case I had to use a comparable interface and a compareTo method).
#Override
public int compareTo(Account anAccount) {
String b = this.title.toString();
Client aTitle = anAccount.title;
String c = aTitle.toString();
if(b.compareTo(c) == 0) {
if(balance == anAccount.balance) {
return 0;
} else if (balance < anAccount.balance) {
return 1;
} else {
return -1;
}
}
return b.compareTo(c);
}
As stated, I had to compare both object values first, if they are the same I then check the condition of the balance to change the order.
-1 = object is less than the parameter.
0 = when both objects are the same.
1 = the object is more than the parameter.
And I called the method from the Bank.java class with:
Collections.sort(cuentas);
Where cuentas is the ArrayList.

Comparator implementation for sorting the collection [duplicate]

This question already has answers here:
How are Anonymous inner classes used in Java?
(18 answers)
Closed 7 years ago.
Recently I'm trying to get more familiar with the Comparator interface in Java. I have an exercise which is about to sort the ArrayList of strings from the shortest to longest. I used a Comparator of Strings. When searching the net, I found the following solution proposal:
public static Comparator<String> lengthComparator = new Comparator<String>() {
#Override
public int compare(String a, String b) {
if (a.length() == b.length()) {
return a.compareTo(b);
} else {
return (a.length() > b.length() ? 1 : -1);
}
}
};
Then I used it in my code to sort the set:
Collections.sort(set, lengthComparator);
And it worked. What I'd like to ask is the specific way of defining the lengthComparator object here. We create a new object:
new Comparator<String>()
with the default constructor. But then there is a further code with overwritten method in "{}" brackets. Is it a normal way of creating objects? I've never met it before and I'd like to learn more about it. Could you please advise me some referal materials where I can find more informations about it?
Yes this is a common way to create objects, it is called anonymous class.
Comparator is an interface, and you want a class to be instantiated, so you create an object from an anonymous class that implements Comparator.
Anonymous class example
public void sortSetByStringLength(Set set) {
Comparator<String> lengthComparator = new Comparator<String>() {
#Override
public int compare(String a, String b) {
if (a.length() == b.length()) {
return a.compareTo(b);
} else {
return (a.length() > b.length() ? 1 : -1);
}
}
}
Collections.sort(set, lengthComparator);
}
Regular class example
public class LengthComparator implements Comparator<String> {
#Override
public int compare(String a, String b) {
if (a.length() == b.length()) {
return a.compareTo(b);
} else {
return (a.length() > b.length() ? 1 : -1);
}
}
}
And in your program sort a list this way :
public void sortSetByStringLength(Set set) {
Collections.sort(set, new LengthComparator());
}
I'm not sure what's the exact question but as it was already said :
What you have instanciated is an anonymous class. Indeed, as you already know an interface cannot be instanciated.
So, when you do :
new Comparator<String>()
{
#Override
public int compare(String o1, String o2) {
// TODO Auto-generated method stub
return 0;
}
});
it is like you've created a class called let's say : LengthComparator like this :
public class LengthComparator implements Comparator<String>{
public LengthComparator()
{
}
#Override
public int compare(String o1, String o2) {
int ack = 0;
if(o1 == null && o2 == null){
ack = 0;
}
else if(o1 != null && o2 == null){
// Decide what you should do here !
// returnValue = ???
}
else if(o1 == null && o2 != null){
// Decide here, too !
// returnValue = ???
}
else{
if(o1.length() == o2.length()){
// Sort by order ...
ack = o1.compareTo(o2);
}
else{
ack = o1.length() > o2.length() ? 1 : -1;
}
}
return ack;
}
}
As a personal advice, always check your arguments toward null values as you don't really know what is going to be passed in...

Multi column order using java

Hi I need any method or explanation on how we can order multiple column values in java.
The output should be similar to the multiple column order output in MySQL.
for clarification please check the below link
http://www.dynamicdrive.com/forums/showthread.php?19797-ORDER-BY-Multiple-Columns
Let's say your object looks like this:
public DataObject {
public String name;
public int age;
public String hairColour;
}
Let's say you want to sort them based on age, then hair colour, then name. You could create a comparator as follows:
public DataObjectComparator extends Comparator<DataObject> {
public int compare(DataObject o1, DataObject o2) {
// if the age is the same
if(o1.age == o2.age) {
// if the hair colour is the same
if(o1.hairColour.compareTo(o2.hairColour) == 0) {
// return the name comparison
return o1.name.compareTo(o2.name);
} else { // else return the hair colour comparison
return o1.hairColour.compareTo(o2.hairColour);
}
} else { // else return the age comparison
return o1 < o2 ? -1 : 1;
}
}
}
You can sort arraylist for multiple properties using below sample comparator.
public class CustomeClass implements Comparator<CustomeObject> {
public int compare(CustomeObject o1, CustomeObject o2) {
int value1 = o1.prop1.compareTo(o2.prop1);
if (value1 == 0) {
int value2 = o1.prop2.compareTo(o2.prop2);
if (value2 == 0) {
return o1.prop3.compareTo(o2.prop3);
} else {
return value2;
}
return value1;
}
}
Basically it continues comparing each successive attribute of your class whenever the compared attributes so far are equal (== 0).

How to compare both strings and float in compareTo

I am trying to compare both strings and float in the compareTo method but I'm not sure what my final value is going to be.
Below is the compareTo method that I have implemented so far:
ObjectClass otherObj = (ObjectClass)o;
float f1 = this.getValue();
float f2 = otherObj.getValue();
int retValue = Float.compare(f1,f2);
String code1 = this.getCode();
String code2 = otherObj.getCode();
int retValue2 = code1.compareTo(code2);
int finalRet = ??
return finalRet;
if the input is
hashMap.put(new ObjectClass ("20030122", 0.019f), "20030122");
hashMap.put(new ObjectClass ("20030123", 0.019f), "20030123");
hashMap.put(new ObjectClass ("20030124", 0.011f), "20030124");
my output should be in this order
"20030123", 0.019f
"20030122", 0.019f
"20030124", 0.011f
In order to allow your class to be comparable you must implement in it interface Comparable
When the comparison should be based on more then single class member. You compare it sequentially when result of previous was equal to zero. By sequence order you specify the final ordering.
class MyObject implements Comparable<MyObject> {
String message;
long value;
#Override
public int compareTo(MyObject that) {
if(that == null) {
return -1;
}
if(this == that) {
return 0;
}
int result = this.message.compareTo(that.message);
if(result == 0) {
result = Long.compare(this.value,that.value);
}
return result;
}
}
The above example will result with
"20030122", 0.019f
"20030123", 0.019f
"20030124", 0.011f

Filtering and transforming a collection using Google Guava

Imagine the following object
class Trip {
String name;
int numOfTravellers;
DateMidnight from;
DateMidnight too;
}
I have written a manual recursive filter and transform method in java. However, I think this could be written more eloquently using Google Guava.
Can someone help me out and tell me how I can rewrite this to make more readable?
Basically what this method does, is locating equal entries, and combining the ones that are equal by altering the date fields
List<Trip> combineEqual(List<Trip> list) {
int n = list.size() - 1;
for (int i = n; i >= 0; i--) {
for (int j = n; j >= 0; j--) {
if (i == j) {
continue;
}
if (shouldCombineEqual(list.get(i), list.get(j))) {
Trip combined = combine(list.get(i), list.get(j));
list.remove(i);
list.remove(j);
list.add(Math.min(i, j), combined);
return combineEqual(liste);
}
}
}
return list;
}
private boolean shouldCombineEqual(Trip a, Trip b) {
return shouldCombineWith(a, b) || shouldCombineWith(b, a);
}
private boolean shouldCombineWith(Trip a, Trip b) {
return a.too() != null
&& a.too().plusDays(1).equals(b.from)
&& areEqual(a, b);
}
private boolean areEqual(Trip a, Trip b) {
return equal(a.name,b.name) && equal(a.numOfTravellers, b.numOfTravellers);
}
private boolean equal(Object a, Object b) {
return a == null && b == null || a != null && a.equals(b);
}
private Trip combineEqual(Trip a, Trip b) {
Trip copy = copy(a); //Just a copy method
if (a.from.isAfter(b.from)) {
Trip tmp = a;
a = b;
b = tmp;
} // a is now the one with the earliest too date
copy.from = a.from;
copy.too = b.too;
return copy;
}
I don't think Guava can help much here. There's a lot you can improve without it:
Create a TripKey {String name; int numOfTravellers;}, define equals, and use it instead of your misnamed areEqual. Split your trips into lists by their keys - here ListMultimap<TripKey, Trip> can help.
For each key, sort the corresponding list according to from. Try to combine each trip with all following trips. If it gets combined, restart the inner loop only. This should be already much clearer (and faster) than your solution... so I stop here.
I'd just use a HashSet.
First define equals and hashcode in your trip object. Add the first list to the set. Then iterate through the second list checking if a matching trip is already in the set. Something like:
public static Set<Trip> combineEquals(List<Trip> 11, List<Trip> 12) {
Set<Trip> trips = new HashSet<>(11);
for ( Trip t: 12) {
if ( trips.contains(t)) {
// combine whats in the set with t
} else {
trips.add(t);
}
}
return trips;

Categories