如何在 Java 中按值排序 Map
本教程介绍了如何在 Java 中按值对 Map<key, value>
进行排序,并列出了一些示例代码来理解它。
有几种方法可以对 Map
进行排序。这里我们用到了 sort()
、sorted()
方法和 Comparator
接口等。我们来看看例子。
在 Java 中使用 sort()
方法对一个 Map
进行排序
我们可以使用 List
接口的 sort()
方法对 Map 的元素进行排序。sort()
方法将元素按升序排序,我们通过 comparingByValue()
方法指定按值排序。请看下面的例子。
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class SimpleTesting {
public static void main(String[] args) {
Map<Integer, Integer> map = new HashMap<>();
map.put(2, 1020);
map.put(3, 300);
map.put(1, 100);
map.put(5, 500);
map.forEach((k, v) -> System.out.println(k + "=" + v));
System.out.println("After Sorting by value");
List<Entry<Integer, Integer>> list = new ArrayList<>(map.entrySet());
list.sort(Entry.comparingByValue());
list.forEach(System.out::println);
}
}
输出:
1=100
2=1020
3=300
5=500
After Sorting
1=100
3=300
5=500
2=1020
在 Java 中使用 sorted()
方法对 Map
进行排序
如果你正在使用流,你可以使用 sorted()
方法,按升序对元素进行排序。我们将 Map.Entry.comparingByValue()
作为参数传递给 sorted()
方法,以按值对 Map<key, value>
进行排序。
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;
public class SimpleTesting {
public static void main(String[] args) {
Map<Integer, Integer> map = new HashMap<>();
map.put(2, 1020);
map.put(3, 300);
map.put(1, 100);
map.put(5, 500);
map.forEach((k, v) -> System.out.println(k + "=" + v));
System.out.println("After Sorting by value");
Stream<Map.Entry<Integer, Integer>> sorted =
map.entrySet().stream().sorted(Map.Entry.comparingByValue());
sorted.forEach(System.out::println);
}
}
输出:
1=100
2=1020
3=300
5=500
After Sorting by value
1=100
3=300
5=500
2=1020
在 Java 中使用 Comparator
的 sort()
方法对 Map<key, value>
进行排序
在这个例子中,我们使用 compareTo()
方法来比较 sort()
方法内部的 Map<key, value>
的值作为参数。你可以看到,我们创建了一个 Comparator
接口的匿名内类,并定义了 compare()
方法来比较这些值。
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class SimpleTesting {
public static void main(String[] args) {
Map<Integer, Integer> map = new HashMap<>();
map.put(2, 1020);
map.put(3, 300);
map.put(1, 100);
map.put(5, 500);
map.forEach((k, v) -> System.out.println(k + "=" + v));
System.out.println("After Sorting by value");
List<Entry<Integer, Integer>> list = new LinkedList<>(map.entrySet());
Collections.sort(list, new Comparator<Object>() {
@SuppressWarnings("unchecked")
public int compare(Object o1, Object o2) {
return ((Comparable<Integer>) ((Map.Entry<Integer, Integer>) (o1)).getValue())
.compareTo(((Map.Entry<Integer, Integer>) (o2)).getValue());
}
});
Map<Integer, Integer> result = new LinkedHashMap<>();
for (Iterator<Entry<Integer, Integer>> it = list.iterator(); it.hasNext();) {
Map.Entry<Integer, Integer> entry = (Map.Entry<Integer, Integer>) it.next();
result.put(entry.getKey(), entry.getValue());
}
result.forEach((k, v) -> System.out.println(k + "=" + v));
}
}
输出:
1=100
2=1020
3=300
5=500
After Sorting by value
1=100
3=300
5=500
2=1020
使用 Java 中的 sorted()
和 toMap()
方法对一个 Map
进行排序
在这个例子中,我们使用 sorted()
方法对 Map<key, value>
进行排序,并使用 toMap()
方法将结果收集到 LinkedHashMap
中。在这里,我们使用方法引用的概念来创建一个 LinkedHashMap
对象。
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;
public class SimpleTesting {
public static void main(String[] args) {
Map<Integer, Integer> map = new HashMap<>();
map.put(2, 1020);
map.put(3, 300);
map.put(1, 100);
map.put(5, 500);
map.forEach((k, v) -> System.out.println(k + "=" + v));
System.out.println("After Sorting by value");
Map<Integer, Integer> result = map.entrySet()
.stream()
.sorted(Entry.comparingByValue())
.collect(Collectors.toMap(Entry::getKey, Entry::getValue,
(e1, e2) -> e1, LinkedHashMap::new));
result.forEach((k, v) -> System.out.println(k + "=" + v));
}
}
输出:
1=100
2=1020
3=300
5=500
After Sorting by value
1=100
3=300
5=500
2=1020
在 Java 中使用自定义代码对一个 Map
进行排序
在这里,我们创建了一个实现 Comparator
接口的用户自定义类,并将其对象传递给 TreeMap
,以获得按值排序的 Map<key, value>
。
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
class UserComparator implements Comparator<Object> {
Map<Integer, Integer> map;
public UserComparator(Map<Integer, Integer> map) {
this.map = map;
}
public int compare(Object o1, Object o2) {
if (map.get(o2) == map.get(o1))
return 1;
else
return ((Integer) map.get(o1)).compareTo((Integer) map.get(o2));
}
}
public class SimpleTesting {
public static void main(String[] args) {
Map<Integer, Integer> map = new HashMap<>();
map.put(2, 1020);
map.put(3, 300);
map.put(1, 100);
map.put(5, 500);
map.forEach((k, v) -> System.out.println(k + "=" + v));
System.out.println("After Sorting by value");
UserComparator comparator = new UserComparator(map);
Map<Integer, Integer> result = new TreeMap<Integer, Integer>(comparator);
result.putAll(map);
result.forEach((k, v) -> System.out.println(k + "=" + v));
}
}
输出:
1=100
2=1020
3=300
5=500
After Sorting by value
1=100
3=300
5=500
2=1020
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
如何从 Pandas 的日期时间列中提取月份和年份
发布时间:2024/04/23 浏览次数:160 分类:Python
-
我们可以分别使用 dt.year()和 dt.month()方法从 Datetime 列中提取出年和蛾。我们还可以使用 pandas.DatetimeIndex.month 以及 pandas.DatetimeIndex.year 和 strftime()方法提取年份和月份。
如何检查 NaN 是否存在于 Pandas DataFrame 中
发布时间:2024/04/23 浏览次数:208 分类:Python
-
我们可以使用 isnull()和 isna()方法检查 Pandas DataFrame 中是否存在 NaN。
如何在 Pandas DataFrame 的列中将所有 NaN 值替换为零
发布时间:2024/04/23 浏览次数:198 分类:Python
-
在 Pandas 库中使用 df.fillna(),df.replace()方法在 DataFrame 中将 NaN 值替换为零
如何在 Pandas 中更改列的数据类型
发布时间:2024/04/23 浏览次数:183 分类:Python
-
本教程介绍了如何通过使用 to_numaric,as_type 和 infer 对象来更改 Pandas 中列的数据类型。
如何对 Pandas 中的 DataFrame 行随机排序
发布时间:2024/04/23 浏览次数:128 分类:Python
-
我们可以使用 sample(),shuffle()和 permutation()方法随机地对 Pandas 中的 DataFrame 行进行随机排序。
如何获取 Pandas DataFrame 的行数
发布时间:2024/04/23 浏览次数:71 分类:Python
-
本教程介绍如何通过使用 shape,len()来获取 Pandas DataFrame 的行数,以及有多少行元素满足条件。