Map Entry ComparingByValue Sort
Sort map entries by value with Map.Entry.comparingByValue, then chain thenComparing(comparingByKey) so tied values keep a stable order.
Code
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;
public class MapEntrySortByValue {
public static void main(String[] args) {
Map<String, Integer> visits = new LinkedHashMap<>();
visits.put("cart", 3);
visits.put("home", 9);
visits.put("search", 5);
// Entry.comparingByValue:按值排序;值互不相同时结果唯一
visits.entrySet().stream()
.sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
.forEach(entry -> System.out.println("top pages: " + entry));
// 值并列时 HashMap 遍历顺序随机:必须补键名次级排序输出才稳定
Map<String, Integer> withTies = new HashMap<>();
withTies.put("home", 9);
withTies.put("search", 5);
withTies.put("api", 5);
withTies.put("cart", 3);
Map<String, Integer> ranked = withTies.entrySet().stream()
.sorted(Map.Entry.<String, Integer>comparingByValue().reversed()
.thenComparing(Map.Entry.comparingByKey()))
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(a, b) -> a,
LinkedHashMap::new));
System.out.println("ranked map: " + ranked);
}
}How it works
Map Entry ComparingByValue Sort is built around the class MapEntrySortByValue and the function main.
The transformation runs as a stream pipeline — source, intermediate operations, terminal collector — so each stage stays independently readable.
Caveats
- Behavior originates in the standard library alone — no external surface.
Putting it to use
Signature: public static void main(String[] args)
Each run prints the 2 labeled blocks top pages:, ranked map: in source order.
Core lines
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(a, b) -> a,
LinkedHashMap::new));
visits.entrySet().stream()
.sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
.forEach(entry -> System.out.println("top pages: " + entry));
Interactive Tools for This Topic
JSON SorterSort JSON object keys by code point ascending or descending, recursively or top-level only, preserving array order.Line SorterSort text lines ascending or descending with numeric-aware ordering, duplicate removal, empty-line filtering, and locale-aware comparison.SemVer SorterParse and sort Semantic Version 2.0.0 strings with prerelease and build metadata, respecting prerelease-below-release precedence.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What does Map Entry ComparingByValue Sort print when run?
- The script runs standalone; its 2 labeled outputs include `top pages:`, `ranked map:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.