将map排序后输入到text
时间: 2024-05-10 07:20:50 浏览: 7
您可以使用以下代码将Map排序并将其写入文本文件中:
```java
import java.io.*;
import java.util.*;
public class MapSortAndWriteToFile {
public static void main(String[] args) throws IOException {
Map<String, Integer> map = new HashMap<>();
map.put("apple", 10);
map.put("banana", 5);
map.put("orange", 8);
// Sort the map by value in descending order
List<Map.Entry<String, Integer>> list = new ArrayList<>(map.entrySet());
Collections.sort(list, (a, b) -> b.getValue().compareTo(a.getValue()));
// Write the sorted map to a text file
File file = new File("sorted_map.txt");
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
for (Map.Entry<String, Integer> entry : list) {
writer.write(entry.getKey() + " : " + entry.getValue() + "\n");
}
writer.close();
}
}
```
此代码将Map排序并将其写入名为“sorted_map.txt”的文本文件中。在此示例中,我们使用值对Map进行排序。您可以更改比较器以按键或其他条件排序。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)