普歌靈鵠團隊java當中map集合的排序
對map集合當中的key進行排序得到相應的value’的值:
例如:
題:對字串"I LOVE YOU"進行順序的顛倒,使其輸出"YOU LOVE I"?
決議思路:
這道題可以使用map集合當中鍵值對key和value的對應關系,將Integer這個型別給key,String’給value,這樣的話就能用key來給value進行排序,從而達到我們想要的結果,
代碼如下:
package request;
import java.util.*;
public class zhili4 {
//輸入:hello world java 輸出:java world hello,
public static void main(String[] args) {
String[] arr={"I LOVE YOU"};
for (int i=0;i<=arr.length-1;i++){
System.out.println(arr[i]);
}
Map<Integer,String> map= new TreeMap<>(new Comparator<Integer>() {
//這里面是用到了treemap下面排序的一個方法,有順序和倒序,
@Override
public int compare(Integer o1, Integer o2) {
return o2-o1;
}
});
map.put(1,"I");
map.put(2,"LOVE");
map.put(3,"YOU");
for (Map.Entry<Integer,String> entry:map.entrySet()){
System.out.print(entry.getValue()+" ");
}
}
}
下面是運行結果:

希望這個題目使你對集合的理解又更加的深刻,對你有所幫助,謝謝·!
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/272871.html
標籤:java
