Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create unique id (int) from String [closed]

I have a list of models (DocumentSnapshot from Firestore) that have an id (String). I need to create a notification for each of them, they could be many (messages from a chat) and I need to use an int id to assign to the notification. I need to use their String id since I could receive an updated version of that model, so I want to update the notification front that precise model. What could be a solution?

like image 933
4face Avatar asked May 30 '26 06:05

4face


2 Answers

Do it like this

int uniqueNumber = myString.hashCode()

like image 71
Greggz Avatar answered Jun 01 '26 19:06

Greggz


There is inpossible to produce unique int id from infinite set of Strings. But you can use a good hash function for your purpose - in most cases it would be good enough. Please consider using something better than common #hashCode implementation. I would suggest you to look into https://github.com/google/guava/wiki/HashingExplained

and use at least murmur3 algorithm. The code snippet looks like:

import com.google.common.base.Charsets;
import com.google.common.hash.Hashing;

public class Main {

    public static void main(String[] args) {
        System.out.println(
                Hashing.murmur3_32()
                .newHasher()
                .putString("Some Sting", Charsets.UTF_8)
                        .hash().asInt());
    }
}
like image 36
rhkcoo Avatar answered Jun 01 '26 19:06

rhkcoo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!