Sort lists
lambda expression
List<Integer> list = new ArrayList<>();
list.sort((o1, o2) -> {
if (o1.equals(o2)) {
return 0;
}
return o1 > o2 ? 1 : -1; // ascending sort
});
Sort a list and limit the size
class Person {
public String name;
public int age;
}
int sizeLimit = 10;
List<Person> values = new ArrayList<>();
List<Person> valuesSorted = values.stream().sorted(new Comparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
if (o1.age == o2.age) {
return 0;
}
return (o1.age > o2.age) ? -1 : 1; // descending sort
}
}).limit(sizeLimit).collect(Collectors.toList());
Sort object array
Binary search
import java.util.Arrays;
public class Test {
class Plant implements Comparable {
int x;
int y;
@Override
public int compareTo(Object o) {
Plant obj = (Plant) o;
return (this.x == obj.x)? this.y - obj.y : this.x - obj.x;
}
Plant(int x, int y) {
this.x = x;
this.y = y;
}
}
Plant[] arr = {};
Plant ele = new Plant(1, 2);
Arrays.sort(arr);
// binary search
Arrays.binarySearch(arr, ele);
}
Sort maps
Map traversal
public void count(int[] arr)
{
int num=0;
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
for(int i=1; i<=10; i++)
{
map.put(i,num);
}
for(int i=0; i<arr.length; i++)
{
/*Iterator it = map.entrySet().iterator();
while(it.hasNext())
{
Map.Entry m=(Map.Entry)it.next();
if(arr[i]==(int)m.getKey())
map.put((int)m.getKey(),(int)m.getValue()+1);
}*/
for(Map.Entry<Integer,Integer> m:map.entrySet())
{
if(arr[i] == (int) m.getKey())
map.put((int) m.getKey(),(int) m.getValue()+1);
}
}
for(Map.Entry<Integer,Integer> m : map.entrySet())
{
System.out.println(m.getKey() + " count is " + m.getValue() + ".");
}
}
Sort map based on value
HashMap<String, Integer> map = new HashMap<>();
map.put("a",4);
map.put("b", 3);
map.put("c",1);
map.put("d",10);
List<Map.Entry<String,Integer>> list =
new ArrayList<>(map.entrySet());
list.sort(new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Map.Entry<String, Integer> o1,
Map.Entry<String, Integer> o2) {
return (o2.getValue() - o1.getValue());
}
});
for (Map.Entry<String,Integer> item : list) {
System.out.println(item.getKey() + " " + item.getValue());
}
Copyright claim: Java sort tricks is created by melonskin on 2017/07/29. Its copyright belongs to the author. Commercial usage must be authorized by the author. The source should be included for non-commercial purposes.
Link to the article: https://amelon.org/2017/07/29/java-sort.html