`` 通过转换成有序的LinkedHashMap,获取key值对应的下标
public static Integer getStatisticRank(String id, Map<String, Integer> idCntMap , Integer rank){
//排序
LinkedHashMap<String, Long> collect = idCntMap
.entrySet().parallelStream()
.sorted((Map.Entry.<String, Long>comparingByValue().reversed()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
IndexedLinkedHashMap<String, Long> indexedLinkedHashMap = new IndexedLinkedHashMap<>();
collect.forEach(new BiConsumer<String, Long>() {
@Override
public void accept(String k, Long v) {
indexedLinkedHashMap.put(k, v);
}
});
int indexOf = indexedLinkedHashMap.getIndexOf(id);
return NumberUtils.INTEGER_MINUS_ONE.equals(indexOf) ? rank : indexOf + 1 ;
}
package com.ioie.common.utils.stream;
import java.util.ArrayList;
import java.util.LinkedHashMap;
/**
*
* @Description: 获取有序map中key值的下标,通过foreach循环put进ArrayList
*
* @author lld
* @version v1.0.0
* @since 2020-12-18 09:32:02
* @see com.ioie.common.utils.stream
*
*/
public class IndexedLinkedHashMap<K,V> extends LinkedHashMap<K,V> {
/**
* serialVersionUID
*/
private static final long serialVersionUID = 1L;
/**
* 集合
*/
ArrayList<K> arrayList = new ArrayList<K>();
@Override
public V put(K key,V val) {
if (!super.containsKey(key)) {
arrayList.add(key);
}
V returnValue = super.put(key,val);
return returnValue;
}
/**
* 根据值获取下标
* @param i
* @return
*/
public V getValueAtIndex(int i){
return (V) super.get(arrayList.get(i));
}
/**
* 根据下标获取key
* @param i
* @return
*/
public K getKeyAtIndex(int i) {
return (K) arrayList.get(i);
}
/**
* 根据键获取下标
* @param key
* @return
*/
public int getIndexOf(K key) {
return arrayList.indexOf(key);
}
}