I want a strange

There is an array of objects. Each object has a unique id field. I want to convert this array to HashMap with keys equal to this id

Yes, I know how to do this through a cycle. But maybe there is a more elegant way, streams, magic castes, etc. which i just don't know about?

 class Accident{ public int id; .... } Accidents[] accArray = getAccidentsByRetrofitAndGson(); Map accidents<Integer,Accident> = new HashMap(); // Вот вместо этого? for(Accident acc:accidents){ accidents.put(acc.id, acc); } 

    1 answer 1

    Using the forEach method from Stream you can do this:

     Map<Integer, Accident> accidents = new HashMap<>(); Stream.of(accArray).forEach(e -> accidents.put(e.id, e)); 

    By analogy with the option from the comment @post_zeew:

     Map<Integer, Accident> accidents; accidents = Stream.of(accArray).collect(Collectors.toMap(e -> e.id, e -> e)); 
    • IDEA in the face of the compiler swears at mapping, if you do not explicitly cast in Integer - I. Perevoz
    • @ I.Perevoz however this code works . - Regent
    • I wrote about this for those who, using this code in IDEA, will be surprised at “why it does not start” - I. Perevoz