Random ArrayIndexOutOfBoundsException using stream for ordering. Map Elements By Value

in the last days, I am starting to “play” with some Java 8 features, such as stream (I studied a bit of documentation and some examples).

In my application, I have a map, and I need to get the three elements with the highest value (the floating point part).

I tried various modifications of my code (and some of these solutions also: Sort the map <Key, value> by values ​​(Java) ), for example:

Map<Long, Float> great = createMapWith20Elements();
Map<Long, Float> small = great.entrySet().stream()
        .sorted(Map.Entry.<Long, Float>comparingByValue().reversed()) 
        .limit(3) 
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

But reslt is always the same: sometimes the code works fine, the other it gives me

java.lang.ArrayIndexOutOfBoundsException: 19

In rare cases, the border index is 18.

This “random” behavior (18, 19, or the right design) makes me think of the parallel thread problem.

, great 20 ... , :

2,-0.5
3,0.0
4,0.0
5,0.0
6,0.0
7,-0.33333334
8,0.0
9,0.0
10,0.0
11,0.0
12,0.5
13,0.0
14,0.0
15,-0.5
18,0.0
19,0.0
21,0.0
22,0.0
23,0.0
24,0.0

, 17 3... .

?

EDIT:

createMapWith20Elements() , : , 20 , ... .

,

// myIds is an ArrayList<Long>
myIds.parallelStream().forEach(e -> trust.put(e, 0f));
return trust;

myIds.stream() ... , parallelStream (Collection, Stream) (Collection), .

+4
2

, createMapWith20Elements().

(, HashMap TreeMap) , HashMap TreeMap . , ( put) ( ).

:

// myIds is an ArrayList<Long>
myIds.parallelStream().forEach(e -> trust.put(e, 0f));
return trust;

.

// myIds is an ArrayList<Long>
myIds.stream().forEach(e -> trust.put(e, 0f));
return trust;

.

, . :

// myIds is an ArrayList<Long>
Map<Long, Float> syncTrust = Collections.synchronizedSortedMap(trust);
myIds.parallelStream().forEach(e -> syncTrust.put(e, 0f));
return trust;
+4

, , . - , , , .

"Oracle Certified Professional Java SE 8 Programmer II", Sybex:

ArrayList JVM . ArrayList, , . , , , . , , - .

+1

All Articles