Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
192 views
in Technique[技术] by (71.8m points)

sorting - Java - get top 15 from HashMap by rule

I would like to ask for help. Let's say I have HashMap with key-value like this:

String1 0.99
String2 0.98
String3 0.97
String4 0.98
String5 0.5
String6 0.4
String7 0.3
etc.

And I would like to save to array the top 15 entries by this formula: Math.abs(value - 0.5).

The counted values (by the formula) for this data would be:

String1 0.49
String2 0.48
String3 0.47
String4 0.48
String5 0
String6 0.1
String7 0.2

The values sorted

String1 0.49
String4 0.48
String2 0.48
String3 0.47
String7 0.2
String6 0.1
String5 0

And now I would like to have array, where index would be the order and value the original value, like this:

array[0] = 0.99
array[1] = 0.98
array[2] = 0.98
array[3] = 0.97
array[4] = 0.3
array[5] = 0.4
array[6] = 0.5 

Thanks everyone for help

Any help would be appreciated. Thank You

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use Java 8 stream API:

List<Double> result = map.values().stream()
        .map(value -> Math.abs(value - 0.5))
        .sorted()
        .limit(15)
        .collect(toList());

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...