Reputation: 171
I'm trying to sort and print an ArrayList
that is sorted by ID.
clientArr.sort( (p1, p2) -> p1.getAccount().getID().compareTo(p2.getAccount().getID()) );
for(Client client : clientArr)
System.out.println(client);
I believe my issue is because p1
and p2
are expecting objects to be returned, but they are getting int
values. How would I go about fixing this?
The ArrayList stores Client objects. Client class contains String values (not important in this example) and it creates an instance of an Account object. Within the Account class is stored the int ID value. That's the value I need
Upvotes: 2
Views: 178
Reputation: 201527
Use Integer.compare(int, int)
like,
clientArr.sort((p1, p2) -> Integer.compare(p1.getAccount().getID(),
p2.getAccount().getID()));
Also, your for-each
loop could be rewritten like
clientArr.forEach(System.out::println);
Upvotes: 6
Reputation: 1211
You can do all this stuff in just one go and in a functional way that Java8 suggests -
Use sorted of Stream API and provide a comparator as the method reference.
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class ComparingTest {
public static void main(String[] args) {
List<Test> mTestList = new ArrayList<>();
mTestList.add(new Test(10));
mTestList.add(new Test(1));
mTestList.add(new Test(5));
mTestList.add(new Test(4));
mTestList.add(new Test(2));
mTestList.add(new Test(8));
mTestList.add(new Test(7));
mTestList.stream().sorted(Comparator.comparingInt(Test::getId)).forEach(System.out::println);
}
}
class Test {
public int id;
Test(int id) {
this.id = id;
}
public int getId() {
return id;
}
@Override
public String toString() {
return String.valueOf(getId());
}
}
Upvotes: 1