Home Java javaTutorial Implementation method of JavaMap sorting by Value

Implementation method of JavaMap sorting by Value

Jan 19, 2017 am 09:48 AM

Map is a collection interface of key-value pairs. Its implementation classes mainly include: HashMap, TreeMap, Hashtable and LinkedHashMap, etc.

•TreeMap: A NavigableMap implementation based on a Red-Black tree, which is sorted according to the natural ordering of its keys, or according to the Comparator provided when the map is created, depending on the Construction method.

•The value of HashMap is not in order. It is implemented according to the HashCode of the key. How do we implement sorting for this unordered HashMap? Refer to the value sorting of TreeMap.

Map.Entry returns the Collections view.

Sort by key

TreeMap is in ascending order by default. If we need to change the sorting method, we need to use a comparator: Comparator. Comparator is a comparator interface that can sort collection objects or arrays. Sorting can be achieved by implementing the public compare(T o1, To2) method of this interface.

Note: The following codes have been tested and passed in Jdk1.6

TreeMap is sorted by key in ascending order by default

public static void keyUpSort() {
// 默认情况,TreeMap按key升序排序
Map<String, Integer> map = new TreeMap<String, Integer>();
map.put("acb1", 5);
map.put("bac1", 3);
map.put("bca1", 20);
map.put("cab1", 80);
map.put("cba1", 1);
map.put("abc1", 10);
map.put("abc2", 12);
// 默认情况下,TreeMap对key进行升序排序
System.out.println("------------正常情况,TreeMap按key升序排序--------------------");
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + ":" + entry.getValue());
}
}
Copy after login

Modify the sorting method of TreeMap, Sort by key in descending order

public static void keyDownSort() {
// TreeMap,按key降序排序
// 降序排序比较器
Comparator<String> keyComparator = new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
// TODO Auto-generated method stub
return o2.compareTo(o1);
}
};
Map<String, Integer> map = new TreeMap<String, Integer>(keyComparator);
map.put("acb1", 5);
map.put("bac1", 3);
map.put("bca1", 20);
map.put("cab1", 80);
map.put("cba1", 1);
map.put("abc1", 10);
map.put("abc2", 12);
System.out.println("------------TreeMap按key降序排序--------------------");
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + ":" + entry.getValue());
}
}
Copy after login

Sort by Value

The following only demonstrates sorting by Value in ascending order by TreeMap, which also applies to HashMap.

Modify the sorting method of TreeMap and sort in ascending order of Value

Note: Under normal circumstances, Map cannot be sorted using the Collections.sort() method, but it can be converted into a list. Sort again.

public static void valueUpSort() {
// 默认情况,TreeMap按key升序排序
Map<String, Integer> map = new TreeMap<String, Integer>();
map.put("acb1", 5);
map.put("bac1", 3);
map.put("bca1", 20);
map.put("cab1", 80);
map.put("cba1", 1);
map.put("abc1", 10);
map.put("abc2", 12);
// 升序比较器
Comparator<Map.Entry<String, Integer>> valueComparator = new Comparator<Map.Entry<String,Integer>>() {
@Override
public int compare(Entry<String, Integer> o1,
Entry<String, Integer> o2) {
// TODO Auto-generated method stub
return o1.getValue()-o2.getValue();
}
};
// map转换成list进行排序
List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String,Integer>>(map.entrySet());
// 排序
Collections.sort(list,valueComparator);
// 默认情况下,TreeMap对key进行升序排序
System.out.println("------------map按照value升序排序--------------------");
for (Map.Entry<String, Integer> entry : list) {
System.out.println(entry.getKey() + ":" + entry.getValue());
}
}
Copy after login

Test results

------------正常情况,TreeMap按key升序排序--------------------
abc1:10
abc2:12
acb1:5
bac1:3
bca1:20
cab1:80
cba1:1
------------TreeMap按key降序排序--------------------
cba1:1
cab1:80
bca1:20
bac1:3
acb1:5
abc2:12
abc1:10
------------map按照value升序排序--------------------
cba1:1
bac1:3
acb1:5
abc1:10
abc2:12
bca1:20
cab1:80
Copy after login

The above is the Java Map introduced by the editor, sorted by Value The implementation method, I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to you in time. I would also like to thank you all for your support of the PHP Chinese website!

For more articles related to the implementation method of JavaMap sorting by Value, please pay attention to the PHP Chinese website!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? Apr 19, 2025 pm 09:51 PM

When using TKMyBatis for database queries, how to gracefully get entity class variable names to build query conditions is a common problem. This article will pin...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

See all articles