How to use Collections.sort() in Java? - java

I got an object Recipe that implements Comparable<Recipe> :
public int compareTo(Recipe otherRecipe) {
return this.inputRecipeName.compareTo(otherRecipe.inputRecipeName);
}
I've done that so I'm able to sort the List alphabetically in the following method:
public static Collection<Recipe> getRecipes(){
List<Recipe> recipes = new ArrayList<Recipe>(RECIPE_MAP.values());
Collections.sort(recipes);
return recipes;
}
But now, in a different method, lets call it getRecipesSort(), I want to sort the same list but numerically, comparing a variable that contains their ID. To make things worse, the ID field is of the type String.
How do I use Collections.sort() to perform the sorts in Java?

Use this method Collections.sort(List,Comparator) . Implement a Comparator and pass it to Collections.sort().
class RecipeCompare implements Comparator<Recipe> {
#Override
public int compare(Recipe o1, Recipe o2) {
// write comparison logic here like below , it's just a sample
return o1.getID().compareTo(o2.getID());
}
}
Then use the Comparator as
Collections.sort(recipes,new RecipeCompare());

The answer given by NINCOMPOOP can be made simpler using Lambda Expressions:
Collections.sort(recipes, (Recipe r1, Recipe r2) ->
r1.getID().compareTo(r2.getID()));
Also introduced after Java 8 is the comparator construction methods in the Comparator interface. Using these, one can further reduce this to 1:
recipes.sort(comparingInt(Recipe::getId));
1 Bloch, J. Effective Java (3rd Edition). 2018. Item 42, p. 194.

Create a comparator which accepts the compare mode in its constructor and pass different modes for different scenarios based on your requirement
public class RecipeComparator implements Comparator<Recipe> {
public static final int COMPARE_BY_ID = 0;
public static final int COMPARE_BY_NAME = 1;
private int compare_mode = COMPARE_BY_NAME;
public RecipeComparator() {
}
public RecipeComparator(int compare_mode) {
this.compare_mode = compare_mode;
}
#Override
public int compare(Recipe o1, Recipe o2) {
switch (compare_mode) {
case COMPARE_BY_ID:
return o1.getId().compareTo(o2.getId());
default:
return o1.getInputRecipeName().compareTo(o2.getInputRecipeName());
}
}
}
Actually for numbers you need to handle them separately check below
public static void main(String[] args) {
String string1 = "1";
String string2 = "2";
String string11 = "11";
System.out.println(string1.compareTo(string2));
System.out.println(string2.compareTo(string11));// expected -1 returns 1
// to compare numbers you actually need to do something like this
int number2 = Integer.valueOf(string1);
int number11 = Integer.valueOf(string11);
int compareTo = number2 > number11 ? 1 : (number2 < number11 ? -1 : 0) ;
System.out.println(compareTo);// prints -1
}

Use the method that accepts a Comparator when you want to sort in something other than natural order.
Collections.sort(List, Comparator)

Sort the unsorted hashmap in ascending order.
// Sorting the list based on values
Collections.sort(list, new Comparator<Entry<String, Integer>>() {
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2)
{
return o2.getValue().compareTo(o1.getValue());
}
});
// Maintaining insertion order with the help of LinkedList
Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
for (Entry<String, Integer> entry : list) {
sortedMap.put(entry.getKey(), entry.getValue());
}

Related

How to sort list of string based on custom logic in java

I have an arraylist with values ... ST1000, ST 5000, ST 30000, ST400, ST500, SP1000, SP600
I want it o be sorted like ST1000, ST2000, ST3000, ST4000, SP600, SP1000 .. How can I do that?
Thanks
you can use the compareTo which will compare it for you lexicographically
here are 2 methods to sort your list using java 8
list.stream()
.sorted((s1, s2) -> s1.compareTo(s2)).collect(Collectors.toList());
list.sort((s1, s2)->s1.compareTo(s2));
using java 8, you don't have to use Collections.sort method
You can sort any collection in a desired manner with a Collections.sort(List<T> list, Comparator<? super T> c) method.
All you need to do is to realize Comparator's compare method accordingly.
In your particular case it would go something like this:
List<String> list = Arrays.asList("ST1000", "ST5000", "ST30000", "ST400", "ST500", "SP1000", "SP600");
Collections.sort(list, new Comparator<String>() {
#Override
public int compare(String o1, String o2) {
String o1Prefix = o1.substring(0, 2);
String o2Prefix = o2.substring(0, 2);
if (o1Prefix.equals(o2Prefix)) {
return Integer.parseInt(o1.substring(2, o1.length())) > Integer.parseInt(o2.substring(2, o2.length())) ? 1 : -1;
} else if (o1Prefix.equals("ST")) {
return -1;
} else {
return 1;
}
}
});
YOu can create a custom Comparator object and override compare method with the desired logic.
Comparator<Model> customComparator = new Comparator<Model>() {
public int compare(Model arg0, Model arg1) {
//TODO custom sort logic
}
};
if compare returns -1 then the arg0 is less than arg1 , 0 equals and 1 greater
then sort the list using the custom comparator
Collections.sort(list, customComparator);

Iterate through a hashmap?

I am trying to make kind of highscores in Java.
Basically I want a hashmap to hold the double value (so index starts from the highest double, so it's easier for me to sort highscores) and then the second value will be the client object, like this:
private HashMap<Double, TempClient> players = new HashMap<Double, TempClient>();
And to insert a new value:
TempClient client = new TempClient(kills, rank, deaths, name);
this.players.put(client.getKdr(), client);
Now, of course I can't iterate through the hashmap because it gets the list item by key, not index.
How can I iterate through a hashmap? or any good ideas for my case?
I tried it in a Foo class:
Output:
0.5
0.6
0.9
0.1
2.5
Code:
public class Foo {
public static void main(String[] args) {
HashMap<Double, String> map = new LinkedHashMap<Double, String>();
map.put(0.5, "hey");
map.put(0.6, "hey1");
map.put(0.9, "hey2");
map.put(0.1, "hey425");
map.put(2.5, "hey36");
for (Double lol : map.keySet()) {
System.out.println(lol);
}
}
}
You can iterate like this.
for (Double k : players.keySet())
{
TempClient p = players.get(k);
// do work with k and p
}
If you want to keep keys sorted, use e.g. a TreeMap.
If you want to keep the keys in the order you inserted
them in there, use e.g. a LinkedHashMap.
The best way is to iterate through hashmap is using EntrySet.
for (Map.Entry<Double, TempClient> entry : map.entrySet()) {
Double key= entry.getKey();
TempClient value= entry.getValue();
// ...
}
You'd be better off making your TempClient objects implement Comparable, adding them to a list, and then just using Collections.sort().
Since you can't sort items in a HashMap, nor you can sort them by value in a TreeMap you could use a TreeSet with a custom class:
class Score implements Comparable<Score>
{
final Player player;
final int score;
Score(Player player, int score) {
this.player = player;
this.score = score;
}
public int compareTo(Score other) {
return Integer.compare(this.score, other.score);
}
public int hashCode() { return player.hashCode(); }
public boolean equals(Object o) { return this.player.equals(...); }
}
TreeSet<Score> scores = new TreeSet<Score>();
score.add(new Score(player, 500));
for (Score s : scores) {
..
}
This will have both the advantages:
it will be iterable
it will keep scores automatically sorted
It should work easily with consistente between equals, hashCode and compareTo but maybe you should tweak something (since it's untested code).

Order the elements of array list in Java

I have an arraylist defined whose elements are say, [man, animal, bird, reptile]. The elements in the arraylist are non-mandatory. The list can even be empty.
I always need to give the output as [animal,man,reptile,bird]. Means, the order of the elements are to be maintained. Is there any way of doing in arraylist?
I thought I can do like
for (String listElement: customList) { //custom list variable holds all elements
if (listElement.equalsIgnoreCase("animal"){
newList.add(0, listElement);
} else if("man") {
newlist.add(1, listElement);
}
But I would want to know the best practice of doing. Can someone please help me on this?
You can define a custom sorting and use it to order your array (save the comparator somewhere, so you don't have to instantiate it many times):
List<String> definedOrder = // define your custom order
Arrays.asList("animal", "man", "reptile", "bird");
Comparator<String> comparator = new Comparator<String>(){
#Override
public int compare(final String o1, final String o2){
// let your comparator look up your car's color in the custom order
return Integer.valueOf(definedOrder.indexOf(o1))
.compareTo(Integer.valueOf(definedOrder.indexOf(o2)));
}
};
Collections.sort(myList, comparator);
Use a custom comparator:
Collections.sort(customList, comparator);
int i = 0;
for (String temp : customList) {
System.out.println("customList " + ++i + " : " + temp);
}
Custom comparator below:
public static Comparator<String> comparator = new Comparator<String>() {
public int compare(String str1, String str2) {
return orderOf(str1) - orderOf(str2);
}
private int orderOf(String name) {
return ((List)Arrays.asList("animal", "man", "reptile", "bird")).indexOf(name);
}
};
You can use Collections.sort(yourArrayList, new CustomComparator());
You need to create your own comparator for this, though, but it is easy.
public class CustomComparator implements Comparator<YourType>{
#Override
public int compare(YoyrType o1, YoyrType o2) {
// logic for ordering the list
}
}
arraylist is ordered.
maybe you want to insert element into the list.
could you create a new list every time when you have to insert and copy each of them?

Sort an ArrayList base on multiple attributes

I have an ArrayList of object. The object contain attributes date and value. So I want to sort the objects on the date, and for all objects in the same date I want to sort them on value. How can I do that?
Implement a custom Comparator, then use Collections.sort(List, Comparator). It will probably look something like this:
public class FooComparator implements Comparator<Foo> {
public int compare(Foo a, Foo b) {
int dateComparison = a.date.compareTo(b.date);
return dateComparison == 0 ? a.value.compareTo(b.value) : dateComparison;
}
}
Collections.sort(foos, new FooComparator());
public static <T> void sort(List<T> list, final List<Comparator<T>> comparatorList) {
if (comparatorList.isEmpty()) {//Always equals, if no Comparator.
throw new IllegalArgumentException("comparatorList is empty.");
}
Comparator<T> comparator = new Comparator<T>() {
public int compare(T o1, T o2) {
for (Comparator<T> c:comparatorList) {
if (c.compare(o1, o2) > 0) {
return 1;
} else if (c.compare(o1, o2) < 0) {
return -1;
}
}
return 0;
}
};
Collections.sort(list, comparator);
}
Java-8 solution using Stream API:
List<Foo> sorted = list.stream()
.sorted(Comparator.comparing(Foo::getDate)
.thenComparing(Foo::getValue))
.collect(Collectors.toList());
If you want to sort the original list itself:
list.sort(Comparator.comparing(Foo::getDate)
.thenComparing(Foo::getValue));
If you want sample code looks like, you can use following:
Collections.sort(foos, new Comparator<Foo>{
public int compare(Foo a, Foo b) {
int dateComparison = a.date.compareTo(b.date);
return dateComparison == 0 ? a.value.compareTo(b.value) : dateComparison;
}
});
If the class of the object implements Comparable, then all you need to do is properly code the compareTo method to first compare dates, and then if dates are equal, compare values, and then return the appropriate int result based on the findings.

Comparator interface

ok I was going to edit my previous question but i wasnt sure if it was the right way to do it so i'll just give another question about Comparator, now i want to be able to sort with different ways. I have a bank checks and i want to sort with checkNumber then checkAmount
i managed to do it with checkNumber but couldnt figure out how with checkAmount
here is how i did it for checkNumber:
import java.util.Comparator;
public class Check implements Comparator {
private int checkNumber;
private String description;
private double checkAmount;
public Check() {
}
public Check(int newCheckNumber, double newAmountNumber) {
setCheckNumber(newCheckNumber);
setAmountNumber(newAmountNumber);
}
public String toString() {
return checkNumber + "\t\t" + checkAmount;
}
public void setCheckNumber(int checkNumber) {
this.checkNumber = checkNumber;
}
public int getCheckNumber() {
return checkNumber;
}
public void setAmountNumber(double amountNumber) {
this.checkAmount = amountNumber;
}
public double getAmountNumber() {
return checkAmount;
}
#Override
public int compare(Object obj1, Object obj2) {
int value1 = ((Check) obj1).getCheckNumber();
int value2 = ((Check) obj2).getCheckNumber();
int result = 0;
if (value1 > value2){
result = 1;
}
else if(value1 < value2){
result = -1;
}
return result;
}
}
import java.util.ArrayList;
import java.util.Collections;
import test.CheckValue;
public class TestCheck {
public static void main(String[] args) {
ArrayList List = new ArrayList();
List.add(new Check(445, 55.0));
List.add(new Check(101,43.12));
List.add(new Check(110,101.0));
List.add(new Check(553,300.21));
List.add(new Check(123,32.1));
Collections.sort(List, new Check());
System.out.println("Check Number - Check Amount");
for (int i = 0; i < List.size(); i++){
System.out.println(List.get(i));
}
}
}
thank you very much in advance and please tell me if im submiting things in the wrong way.
What you really want to do is define a separate class to act as the Comparator object - don't make your actual Check class the comparator, but instead have 3 classes:
the Check class itself
a CheckAmountComparator class (or something similar) that implements Comparator<Check>
a CheckNumberComparator class (or something similar) that implements Comparator<Check>
Then when you want to sort one way or another, you simply pass an instance of the Comparator-implementing class corresponding to the type of sorting you want to do. For instance, to sort by amount, it'd then become...
Collections.sort(yourListVariable, new CheckAmountComparator());
Also - I'd highly suggest naming your variable something other than List, since List is used as a type name in Java.
You should make Check implements Comparable<Check>, but not itself implements Comparator.
A Comparable type defines the natural ordering for the type, and a Comparator for a type is usually not the type itself, and defines their own custom ordering of that type.
Related questions
When to use Comparable vs Comparator
Java: What is the difference between implementing Comparable and Comparator?
Can I use a Comparator without implementing Comparable?
Also, you shouldn't use raw type. You need to use parameterized generic types, Comparable<Check>, Comparator<Check>, List<Check>, etc.
Related questions
What is a raw type and why shouldn’t we use it?
A String example
Let's take a look at what String has:
public final class String implements Comparable<String>
String defines its natural ordering as case-sensitive
It has a field
public static final Comparator<String> CASE_INSENSITIVE_ORDER
Here we have a case-insensitive custom Comparator<String>
An example of using this is the following:
List<String> list = new ArrayList<String>(
Arrays.asList("A", "B", "C", "aa", "bb", "cc")
);
Collections.sort(list);
System.out.println(list);
// prints "[A, B, C, aa, bb, cc]"
Collections.sort(list, String.CASE_INSENSITIVE_ORDER);
System.out.println(list);
// prints "[A, aa, B, bb, C, cc]"
Here's an example of sorting List<String> using both its natural ordering and your own custom Comparator<String>. Note that we've defined our own Comparator<String> without even changing the final class String itself.
List<String> list = new ArrayList<String>(
Arrays.asList("1", "000000", "22", "100")
);
Collections.sort(list);
System.out.println(list);
// prints "[000000, 1, 100, 22]" natural lexicographical ordering
Comparator<String> lengthComparator = new Comparator<String>() {
#Override public int compare(String s1, String s2) {
return Integer.valueOf(s1.length())
.compareTo(s2.length());
}
};
Collections.sort(list, lengthComparator);
System.out.println(list);
// prints "[1, 22, 100, 000000]" ordered by length
Comparator<String> integerParseComparator = new Comparator<String>() {
#Override public int compare(String s1, String s2) {
return Integer.valueOf(Integer.parseInt(s1))
.compareTo(Integer.parseInt(s2));
}
};
Collections.sort(list, integerParseComparator);
System.out.println(list);
// prints "[000000, 1, 22, 100]" ordered by their values as integers
Conclusion
You can follow the example set by String, and do something like this:
public class Check implements Comparable<Check> {
public static final Comparator<Check> NUMBER_ORDER = ...
public static final Comparator<Check> AMOUNT_ORDER = ...
public static final Comparator<Check> SOMETHING_ELSE_ORDER = ...
}
Then you can sort a List<Check> as follows:
List<Check> checks = ...;
Collections.sort(checks, Check.AMOUNT_ORDER);

Categories

Resources