in the last days I'm starting to "play" with some Java 8 features, like stream (I studied a bit of documentation and several examples).
In my application I have a Map and I need to get the three element with highest value (the float part).
I tried different modifications to my code (and some of these solutions also: Sort a 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 the reslt is always the same: sometimes the code works fine, other it gives me a
java.lang.ArrayIndexOutOfBoundsException: 19
In rare cases, the index out of the bounds is 18.
This "random" behaviour (18, 19, or correct elaborations) makes me think to a "parallel threading" problem.
I'm sure that great
map has always 20 elements... if I print them I receive:
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
I'm conscious that 17 objects are candidate to be the first 3... but it is not a problem for my algorithm.
Can you help me in some way?
Thanks
EDIT:
The method createMapWith20Elements()
has a dummy name for better explaining my situation: I'm sure it returns 20 elements because it makes a DB reading... but it should return any matching record.
By the way it ends with
// myIds is an ArrayList<Long>
myIds.parallelStream().forEach(e -> trust.put(e, 0f));
return trust;
Replacing with myIds.stream()
it seems working fine... I'm not able to figure how using parallelStream
to write to an object (Collection
and not Stream
), and returning the object itself (Collection
), in the calling function it can lead to this kind of problem.