Java Key Generator From String
$begingroup$ I think the probability of having a duplicate is much higher. Let us take the alphabet of 32 characters and only 4 characters long output string. This has 32^4=1048576 of possible options. Using the formula generating 100.000 unique entries has the likelyhood of not having any duplicates 0.909 which seems a lot. But let say you wish to have have just one new unique value, you.
- Public CombinedCipherOutputStream(OutputStream out, Cipher asym, String algorithm) throws IOException, GeneralSecurityException super (out); // create a new symmetric cipher key used for this stream String keyAlgorithm = getKeyAlgorithm(algorithm); SecretKey symKey = KeyGenerator. GetInstance (keyAlgorithm). GenerateKey ; // place the symmetric key by encrypting it with.
- Using the KeyGenerator class and showing how to create a SecretKeySpec from an encoded key: Key Generator « Security « Java.
- Generate 20 character long alphanumeric string randomly using Charset which is in java.nio.charset package. First take char between 0 to 256 and traverse. Check char is alphabetic or numeric. If yes, then add at the end of our String; Return String; Below is the implementation of the above approach.
Today we’ll look at creating generators. In simple terms, a generator is a function which returns the next value in a sequence. Unlike an iterator, it generates the next value when needed, rather than returning the next item of a pre-generated collection. Some languages such as Python support generators natively via keywords such as yield. When a generator’s next value is requested in Python, the generator function continues to run until the next yield statement, where a value is returned. The generator function is able to continue where it left off which can be quite confusing for the uninitiated. So how to do something similar in Java?
We saw in the last article that we can use an IntStream to generate a simple set of numbers, but we had to generate them all up front. That’s fine if we know how many we’re going to need. What if we don’t, and we want to be able to get the next whenever we like? This is where a generator comes in.
Let’s choose a simple infinite sequence, the square numbers. In a standard Java implementation we’d end up with something like the following:
This prints the first three square numbers. Note we could have gone further and implemented this as an iterator.
What we have here is an example of lazy evaluation in a non-functional style. Wikipedia defines lazy evaluation as: ‘In programming language theory, lazy evaluation, or call-by-need is an evaluation strategy which delays the evaluation of an expression until its value is needed’. Lazy evaluation is useful because we don’t need to worry about infinite sequences, performing computationally expensive operations up-front, and about storage.
Let’s expand on the example to allow getting a batch of results. This is easy – create a nextN function which calls next() a number of times and returns the results in say a List:
A few points:
- Notice in the nextN function there is the empty diamond in the new ArrayList statement. This was added in Java 7 to save having to state the type both on the left and the right hand side; the compiler now works it out.
- List is an Iterable, and Iterable now has a forEach() method which was added in Java 8. We could use stream() as before to create a stream, but if all we want to do is pass the contents to a function forEach() does nicely.
Now, to save having to write nextN for every sequence we make, we could create a new type which extends Iterator providing the nextN function.
The only problem we face here is that we have to save the batch in a list before we can operate on it. Java 8 provides another way. Let’s go back and start again with the following code:
This uses IntStream to get the indexes of the sequence in a stream and calls map to convert them into their squares. The problem is that to get more squares than the tenth we need to duplicate the pipeline and start it off from the right place. Let’s look at another way without using a range:
This also generates the first 10 square numbers. This time it uses the iterate function. This takes two parameters, the first is our initial value, and the second is a function defining how to get to the next value from the previous. It’s a good place to use a lambda function. We can even dispense of the map function since we can undo squaring easily in iterate to get what the last index was:
This solves one of the problems of having to buffer beforehand. However, we need to use the limit operator on the stream to limit it to 10 items, otherwise it would keep on going. Unfortunately this is a problem, since once we’ve got the 10 the stream is ‘operated on’ and we can’t use it again to generate more. If we try, we get an IllegalStateException. We’d have to create another stream to get more.
So how do we get around the problem of the stream being used up? Instead of using IntStream’s iterate function, we can use generate instead. IntStream’s generate function takes an instance of an IntSupplier. IntSupplier has a getAsInt() function which returns the next int in the sequence which is very much like our next() function. Here is an example that prints the first 20 square numbers in two batches:
Again we’re using limit to stop the stream continuing indefinitely. However unlike last time, although the stream is used up, the generator still survives and can be used again. No buffering needed either, just keeping hold of the supplier. The only downside vs the old Java way is that we have to use Streams to get sequence members, although this comes with other benefits such as parallelism which we’ll see in a later article.
Overall, there are several ways to generate a sequence and which we chose may depend on our needs. Using an IntSupplier is a good way to integrate with the rest of the Java 8 functional programming support.
how can i create this key from the string.
Please help ! !
I presume you can't implement the Comparable interface? Can you create a Comparator?
If you put Strings as Keys in a Map, I didn't think there was any limit to its length.
Have I misunderstood your question?
There is no free lunch here. You can shorten a string, but you will lose data, and hence, accuracy in comparison. Generally, shortening a string is useful, if you only care to detect if two strings are *not* equal. The easiest way is to use the hashcode, since if two strings are not equal, then their hashcodes are not equal either. Another way is to use a message digest, such as MD5 or SHA1, but again, like with hashcode, it is possible for two unequal strings to have the same digest.
Henry
Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
inside my main object there are lot of sub objects. this main object is not just a string. so I create a unique string using the data inside this main object. this key would be length of 100 charactors.sometimes more than that. it depend on the data inside the main object.
And i have around 250 main objects to compare each other. so still you propose to keep the string key as the Map key?
I thought to use MD5 and create a hashcode.
also can two unequal objects have same hashcode if i use MD5?
Imesh
can two unequal objects have same hashcode if i use MD5?
No free lunch. Yes, they can.
However, MD5 tries its best to have two objects that are very similar to have different digests. Meaning, if two strings are off by only one or two characters, then it is highly unlikely that the two digests are the same. On the other hand, if two strings are completely different, then it has a better chance that the digests are the same.
Henry
/quick-heal-antivirus-pro-2017-product-key-generator.html. Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Imesh Damith wrote:also can two unequal objects have same hashcode if i use MD5?
Yes they can, as Henry already said. Hash codes, in whatever form, are not going to help you here. It's theoretically impossible to make it so that two unequal objects always have different hash codes - if that would be possible, you'd have invented an incredible compression algorithm that violates the laws of information theory.
Generate Random String Java
It's easy to see why this is theoretically impossible. Suppose you have a block of data containing N bits. Then there are 2^N possible ways you could fill this block of data. Now, you're going to calculate an M-bit hash code over the block of data (where M < N). So there are 2^M possible hash codes. Since M < N, 2^M < 2^N, so there are less possible hash codes than blocks of data. This means that there must be different blocks of data that have the same hash code.
Thanks for the explenation, so is there anyway that i can solve my problem? do i have to keep lengthy string itself as the key in the map?
Thanks
Imesh
In my answer above I said that hash codes are not going to help you. That's maybe not entirely true - you can use hash codes to make comparisons faster. That's how collections such as HashSet and HashMap in the standard Java API work. But you will still need a way to compare the complete content of objects.
To compare two objects, you could do this:
1. Check if the hash codes of the two objects are different. If they are, then you're done; the two objects are different.
2. If the hash codes are equal, then you need to compare the full content of the two objects to determine if they are equal or not.
If you do it that way, then you only need to do a full comparison if the hash codes of the two objects are equal.
I don't know how performance critical your code is, but on a normal computer strings of 100 characters and 250 objects that you need to compare can be done in a small fraction of a second. Don't waste too much time on performance optimization if you don't know that there's a performance problem.
Java Key Input
java StringHashDemo Campbell
text length: 10000008, starts like this: Campbell멓㕑Campbellꀺ剂CampbellꚲCampbell㡗罴Campbell噠떻Campbell꾌뷭Campbell꾱Campbell竵컗Campbell읥?Campbell雦Campbell⛅䕴Campbell䞈躧CampbellCampbell炂滕Campbell䕘鷎Campbell푽쩊Campbell줕쬃Campbell苀횂CampbellꞲඐCampbell葻촻Campbell–纇Campbell佺Campbell諚嗝Campbell㺭Campbell폖썉Campbell퀿훂Campbell毆饐Campbell暼∙Campbell㩇뤃Campbell齋킎Campbellწ矒Campbell嶔Campbell?婴Campbell㹇끋CampbellᤘࢫCampbell怚捳Campbell偑栛Campbell䦡ᕟCampbell⎀焰Campbellེ倏Campbell睚כCampbell봰癚CampbellCampbell愧驉Campbell羗偎Campbell墘矸Campbell뼛靼Campbell욌Campbell熇놂Campbell旱Campbell풰Campbell涼నCampbellㅰ砬Campbell욪뒂Campbell轗ݣCampbell㦸벱CampbellⲖ㊣Campbell檫ȐCampbell剟ęCampbell䅲炘Campbell▪࿎Campbell閹쮪Campbell㵢䨮Campbell鄱箧Campbell풁㺫Campbell霟崜Campbell薨CampbellЩ㏩Campbell䴅ᢙCampbell힉∊Campbell鱧Campbell?Campbell慰⸣Campbell愲?Campbell뢑뻆Campbell浓Campbell玶Campbell䙁惢Campbell퉿燀Campbell໐?Campbell橂阛Campbell襰Campbell纫?Campbell빬㪚Campbell믥↻Campbell泯⊒Campbell≐箞Campbellꇤ㊦Campbell윋긙Campbell䮇Campbell㇘霡Campbell安螪CampbellCampbell态莫Campbell࣑Campbell孵멒Campbellΐ认Campbellệ쏦Campbellड़Campbellௌ
. . . and the hashcode for that object follows, taking 50497.219 μs to work out . . . d10dfa69
Java String Api
Imesh