15,322 questions
Best practices
0
votes
3
replies
82
views
Does it safe to modify the oldValue of remappingFunction in java.util.Map#merge?
I want to implement something like this:
Map<String, List<String>> m = new HashMap<>();
for (... in ...) {
String key = ...;
String val = ...;
m.merge(key, Lists....
Advice
1
vote
14
replies
250
views
Ordered array vs. hash map in c++ (100 elements)
I need help regarding a code I want to write in c++.
I want to develop a program that receives and visualizes CAN messages on a GUI. The messages in question are about 100 distinct ID's, so we're not ...
5
votes
2
answers
139
views
How to more nicely pull all values from hash that aren't a given key?
I know how to get all of the values of a hash given a set of keys:
use strict;
use warnings;
use DDP;
my %h = (
a => 1,
b => 2
);
my @v = @h{a,b};
p @v; # ( 1, 2 )
However I'm not sure ...
1
vote
2
answers
151
views
How do I get all keys of a maximum value from a HashMap in Rust?
In Rust, how can I get all keys from a HashMap that have a maximum value?
Say I have something like this:
let words = vec!["Hello", "World", "Hello", "everybody"...
3
votes
1
answer
196
views
Custom hasher is faster for insert and remove, but when done together is slower, when comparing to std::collections::HashMap
I wish to benchmark various hashmaps for the <K,V> pair <u8, BoxedFnMut> where BoxedFnMut.
type BoxedFnMut = Box<dyn FnMut() + Send + 'static>;
To do this, I am using divan(0.1.21) ...
3
votes
2
answers
162
views
Mixed-type hash table design
I think this is a design problem. I’m trying to implement a hash table library in C89 in which the user will be able to insert mixed-type literal keys and values, e.g., HT_SET_LITERAL(&ht, "...
0
votes
2
answers
117
views
If I specify the capacity of a dictionary through the constructor, should I use a prime? [closed]
I am initializing a fairly large dictionary in C#.
I have benchmarked the speed of building the dictionary with the capacity and without. It is (as expected) significantly faster (and uses ...
-7
votes
1
answer
94
views
Stuck at a test case cant understand the prolem [closed]
I am trying to improve my coding skills and I got stuck at a question and can't understand the test case. I passed the first 5 test cases but got stuck at the last one:
Top K Frequent Elements
Given ...
0
votes
0
answers
50
views
What's the differences between using is_transparent = void vs std::false_type vs std::true_type? [duplicate]
Say I want to enable heterogeneous lookup for associative containers by the Compare below, what difference does the type of tag is_transparent make?
struct Compare {
// What difference do the ...
0
votes
1
answer
70
views
Couldn't understand on how lookup in a hashmap is O(N) while iterating over the same [duplicate]
I was doing leet code and came across https://leetcode.com/problems/two-sum/description/, which I've tried solving with a seen counter using hashmap. Below is the code:
class Solution:
def twoSum(...
0
votes
0
answers
91
views
Double encoded HashMap in rust
I have some data that is a 1:1 map of ids to strings, and I'd love a data structure that lets me query one to get the other. For example:
let mut map:DoubleMap<i32,String> = DoubleMap::new();
...
2
votes
4
answers
408
views
How to define Rust HashMap where the keys are refences to the values?
I am porting some of my more complex C++ code over to Rust as a way to learn the language. One thing I have is a map of values keyed by a std::string held inside the value type, to avoid copying the ...
0
votes
0
answers
87
views
Having a class that supports operator overloads for both itself, a hashmap overload
I have a custom Node class that needs to be used with a custom hashmap and compare value eg. std::unordered_map<std::shared_ptr<Node>, double, Node::Hash, Node::Compare> neighbors;
Right ...
-3
votes
1
answer
122
views
PriorityQueue Comparator weird behavior when sort order is fetched from hashmap
While working in LeetCode 675, I came across a weird behavior with PriorityQueue Comparator that I can't explain.
For brevity, I'll state the gist of the problem statement; interested parties can read ...
2
votes
1
answer
123
views
Java how does searching for a key in a HashMap bucket work?
EDIT: As one of the people commenting mentioned, this question only concerns this specific implementation: https://github.com/openjdk/jdk/blob/master/src/java.base/share/classes/java/util/HashMap.java#...
3
votes
2
answers
132
views
Insert to a HashMap if the key doesn't already exist, without cloning the key if it already exists?
I have a HashMap whose key type holds a heap allocation. I don't know if the HashMap already contains a particular key, and I would like to insert a new entry if the key doesn't already exist. How ...
1
vote
1
answer
151
views
Why the performance is bad if I use HashMap to solve Codility problem MinAbsSum?
Regarding the Codility problem MinAbsSum at https://app.codility.com/programmers/lessons/17-dynamic_programming/min_abs_sum/, the performance is bad if I use HashMap to solve the problem. I expect the ...
0
votes
1
answer
147
views
How to group anagrams using collections efficiently? [closed]
I'm working on a Java problem where I need to group words that are anagrams of each other. For instance, given the input array:
["eat", "tea", "tan", "ate", &...
0
votes
0
answers
57
views
Converting a jsonString to HashMap
I have a jsonString which is a list of key value pairs.
[
{"id": "123", "url": "ghi"} : 2,
{"id": "456", "url": "def"} ...
-4
votes
2
answers
174
views
Longest palindrome length algorithm finding incorrect length for long strings
I've been working on this problem:
"Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters. Letters ...
0
votes
1
answer
83
views
Trying to loop getting key-value pairs from a json file in Rust to populate a map
I'm still fairly new to rust (coming from PHP), currently trying to teach myself trial by fire by working on a passion project in it.
For one of my mods in the code, I need to process a runtime ...
1
vote
1
answer
162
views
Java PriorityQueue not polling in descending order
Can anyone explain to me why this outputs [accountB(200), accountC(200), accountA(200)] instead of [accountA(200), accountB(200), accountC(200)]?
public static void main(String[] args) {
Map<...
-2
votes
4
answers
209
views
What is difference between Hashmap.get(0) and Hashmap.get(0L)? [duplicate]
I have:
HashMap<Long, MYChainInformation> CHAIN_INFORMATION = new HashMap<>();
When I use this pattern to get element at index 0:
MYChainInformation MyData = CHAIN_INFORMATION.get(0);
...
1
vote
2
answers
1k
views
How should one migrate from lazy_static to std LazyLock/LazyCell
I created a library that uses lazy_static to create a static HashMap that other parts of the code can reference to look up values like this:
use lazy_static::lazy_static;
use std::collections::HashMap;...
1
vote
2
answers
114
views
Powershell hashmap: nested filtering
I’m trying create some automations to help with general activities on an environment and was trying to think of a clean accessible way to store and access info via powershell hashmaps
$test=@{
&...
0
votes
1
answer
215
views
Using Spring Boot JPA to model an entity containing a Map of String's to custom objects
My application uses Spring Boot 3.3.7 with JPA support enabled, which means Hibernate 6 is being used.
I need to define the following Java structure to be persisted using Java entity classes:
A ...
2
votes
0
answers
165
views
Issue with Counting Pairs Matching 𝐴 [ 𝑖 ] + 𝐴 [ 𝑗 ] = 2^ 𝑥 [closed]
Problem Statement:
I am working on a problem where I need to find the number of pairs ( (i, j) ) such that:
( i < j )
( A[i] + A[j] = 2^x ) where ( x ) is an integer.
Since the answer could be ...
7
votes
3
answers
172
views
How to loop through all distinct triplets of an array such that they are of the format (a, b, b)? Length of array <= 10^6
As stated above, I need to efficiently count the number of distinct triplets of the form (a, b, b). In addition, the triplet is only valid if and only if it can be formed by deleting some integers ...
0
votes
1
answer
54
views
given an array of n integers , how can I find any two indices i<j where the absolute difference between the elements equals the distance between i-j
Given an array of n integers in the range [-n²,n²], how can I find any two indices i<j where the absolute difference between the elements equals the distance between their positions?
I'm looking ...
1
vote
1
answer
88
views
the trait `Borrow<String>` is not implemented for `&&str`
I have a code that should combine an array with the names of commands with an array with functions.
use std::{collections::HashMap, env};
fn echo(){}
fn main() {
let names = vec!["echo"...
0
votes
0
answers
62
views
Map Value is Null when Defining PriorityQueue Based on the Map
I have the following code snippet:
Map<Integer, Integer> map = new HashMap<>();
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> map.get(b[1]) == map.get(a[1]) ? b[2] ...
2
votes
1
answer
101
views
Why do I have to use &char instead of char to index a key in a HashMap<char, i32>?
In the following snippet, given the type of 'a' is char, why can't I print letters['a']?
use std::collections::HashMap;
fn main() {
let mut letters = HashMap::new();
for ch in "a short ...
1
vote
1
answer
234
views
how to hash very large numbers into a hash table?
I am not much of a programmer but i have read some where that hash tables are fast when checking existence of data.
I have a list containing 4 million elements of at least 120 bytes each which i need ...
-1
votes
1
answer
87
views
How many pointers does java LinkedHashMap/Set Entry object have
In Java HashSet, when a collision occurs, the HashMap stores multiple entries in the same bucket using a linked list.
Then in the case of LinkedHashSet, LinkedHashMap will have a pointer to the next ...
1
vote
1
answer
190
views
Implementing a Thread-Safe and Efficient Interning Map for Strings in Rust
I’d appreciate help with ensuring thread safety and improving the efficiency of a global string interning map in Rust, particularly when using key-specific locks to manage concurrent access and ...
0
votes
2
answers
92
views
Can't figure out multi-dimensional Perl hash references: Not a HASH reference
Yes, I've looked through many of the "not a HASH reference" articles, but none seem to address my issue. I have a multidimensional hash. Inside a for-loop where I'm a few levels down in my ...
2
votes
4
answers
260
views
Using equals to compare map values returns false even when values and insertion order are the same
I have two Map objects: one HashMap and one LinkedHashMap. Both contain the same values (e.g., [1, 2]), and for the LinkedHashMap, the insertion order is preserved. However, when I compare the ...
0
votes
3
answers
52
views
Why isn't the space complexity of program adding values to a letter keyed hash map linear?
Imagine a program that takes a string of length p as an argument, and counts each letter by adding 1 for every occurrence using a hash map that only uses the 26 letters of the English alphabet as keys....
0
votes
0
answers
159
views
Horrible eBPF performance of TC program on Rust + Aya when reading from HashMap
I'm currently mastering eBPF using Rust + Aya. The following problem has arisen. I'm making a port forwarding program using TC. I record incoming connections in a HashMap and indicate which port it ...
0
votes
0
answers
20
views
How can I insert hashmap values only into Treeset or HashSet
This is my main class:
public class Main {
public static void main(String[] args) throws BookNotFoundException {
// TODO Auto-generated method stub
//Library library = new Library();
...
-2
votes
1
answer
122
views
Confusion around Java HashMap bucketing logic [duplicate]
I was going through the putVal method implementation in the Java HashMap class. Below is the code for reference.
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean ...
1
vote
1
answer
84
views
How i map query result to List<Map<String, Object>
I have a native query in JPA
String sql1 = """
SELECT tier_id, tier_list, vm.id AS model_id, option_list, price, sku, stock
FROM (
...
0
votes
1
answer
97
views
Rust idomatic way to decrementing the value from a map and remove the key when value is 0
Noob to Rust and trying to figure out the idomatic way to decrement the value from a hashmap and remove the corresponding key when the value after decrementing reaches 0.
I am doing it like this but ...
1
vote
1
answer
71
views
Given two Json list how to remove the fields in JSon which are null and not present in the Json list named parsedXmlChild and store it in a new list?
parsedJsonChildData (original data): [{date=null, feeForPerformance=null, feeFrequency=5}, {date=12-25-2024, feeForPerformance=23, feeFrequency=1}, {date=12-03-2025, feeForPerformance=1, feeFrequency=...
0
votes
1
answer
51
views
Simultaneous Mutable and Immutable HashMap gets
I'm working with a struct Node and node_map defined as
pub struct Node<'a> {
id: i32,
next: HashMap<String, &'a Node<'a>>,
}
let mut node_map = HashMap::<i32, ...
4
votes
1
answer
130
views
HashMaps and returning immutable references to inserted keys with std's HashMap (was reference demoting?)
EDIT: After mulling over this topic for a bit, I've become unsure if such an api is inherently possible at all with rust's borrow checker.
So, the APIs I'm trying to achieve (if it did exist in ...
0
votes
4
answers
220
views
Java HashMap iteration order - behavior seems consistent despite documentation stating otherwise [duplicate]
I'm learning about HashMaps in Java and I'm confused about the iteration order. The documentation states that HashMap doesn't guarantee any specific iteration order, but in my simple test, the order ...
2
votes
1
answer
49
views
Does chaining not reduce primary collisions in hashtables?
I had a question on a homework that asked if, for a hashtable, the number of primary collisions would be lower if you chose chaining, linear probing, or quadratic probing.
The answer is that it doesn'...
0
votes
1
answer
261
views
Kotlin serialization of a HashMap
Got an issue with kotlin serialization where I could need some help:
import kotlinx.serialization.json.Json
fun main() {
val someValue: Double = 1.0
val someKey: String? = null
...
0
votes
1
answer
45
views
Is it possible to come up with distinct strings with identical hashcodes algorithmically?
In Java we know some examples of strings which have identical hash codes despite being distinct strings, such as Ea and FB both having a hash code of 2236.
Is there a way, algorithmically, to come up ...