How can I use a HashMap with f64 as key in Rust?

Presented with no comment beyond read all the other comments and answers to understand why you probably don’t want to do this: use std::{collections::HashMap, hash}; #[derive(Debug, Copy, Clone)] struct DontUseThisUnlessYouUnderstandTheDangers(f64); impl DontUseThisUnlessYouUnderstandTheDangers { fn key(&self) -> u64 { self.0.to_bits() } } impl hash::Hash for DontUseThisUnlessYouUnderstandTheDangers { fn hash<H>(&self, state: &mut H) where H: hash::Hasher, { … Read more

Shortcut for adding to List in a HashMap

Since Java 8 you can make use of Map#computeIfAbsent(). Map<String, List<User>> usersByCountry = new HashMap<>(); for (User user : listOfUsers) { usersByCountry.computeIfAbsent(user.getCountry(), k -> new ArrayList<>()).add(user); } Or, make use of Stream API’s Collectors#groupingBy() to go from List to Map directly: Map<String, List<User>> usersByCountry = listOfUsers.stream().collect(Collectors.groupingBy(User::getCountry)); In Java 7 or below, best what you can … Read more