Map排序,Stream流

import java.util.*;

import java.util.Scanner;

import java.util.stream.Collectors;

public class Main {

public static void main(String[] args) {

Scanner in = new Scanner(System.in);

int n = in.nextInt();

int manger = in.nextInt();

Map<String,Integer> map = new LinkedHashMap<>();

for(int i=0; i<n; i++){

map.put(in.next(),in.nextInt());

}

Map<String,Integer> map_new;

if(manger == 0){

map_new = map.entrySet().stream().sorted(Collections.reverseOrder(Map.Entry.comparingByValue())).collect(

Collectors.toMap(

Map.Entry :: getKey,

Map.Entry :: getValue,

(oldVal, newVal) ->oldVal,

LinkedHashMap::new

)

);

} else {

map_new = map.entrySet().stream().sorted(Collections.reverseOrder(Map.Entry.<String,Integer>comparingByValue()).reversed()).collect(

Collectors.toMap(

Map.Entry :: getKey,

Map.Entry :: getValue,

(oldVal, newVal) ->oldVal,

LinkedHashMap::new

)

);

}

map_new.forEach((k,v) -> System.out.println(k + " " + v));

}

}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务