HashMap: How to get keys from value in Java?

To get a set of keys from a value in Java, we can use the below method:

The method getKeysByValue accepts two arguments. The first one is a map in which we want to look for the keys. The second is a searched value. At the beginning of it, we define the set named keys. Nextly, we iterate through the map using its entries. We use the equals() method (from Objects class) to check if values are the same. Then, if we got the searched one we add it to the keys set.

How to cast Double to Integer in Java

To cast Double (not-primitive) value to Integer we can use the intValue() method:

 

To cast double to int you can use the casting operator

 

You can find a detailed description below.

 

1. Object type

It is worth to say that we don’t need to create an object with the new operator when it comes to basic types. Java let us create them like primitive ones automatically converting them to Objects (and vice versa!). It is called autoboxing.

As you can see in the code we take the value from by intValue() method. We can change the type name in method name when we need to cast another type! (e.g. floatValue()).

Obviously code prints:

2. Primitive type

This time we don’t need methods for casting. It is the same like in C++ . We just write (int) before the variable name to cast.

The code prints:

 

How to directly initialize a HashMap in Java

To initialize a HashMap in Java you can use a below syntax:

However, there are also other options. You can find a detailed description below

1. Static initializer

In this option, we declare a static final map with String key and values. Then we make a static initializer and put needed things in it manually. Now, we are 100% sure that this set will be in our HashMap but if we would like to put some other objects in there in the future we can do so.

As a prove, we can print all the values  in main:

2. “Double-brace” syntax

This syntax (also introduced at the beginning of this post) is called double-brace. The first brace creates a new AnonymousInnerClass, the second declares and instance initializer block that is run when the anonymous inner class is instantiated. This kind of initializer is formally called an instance initializer. Sounds complicated, does it? If you want to use this option in your code you need to know how it works and beware of the invisible side effects.

The above code output is:

 

Encode String to UTF-8 in Java

In this short post, we will discuss the String encoding.

1. How do I encode a string to UTF-8?

You cannot.  String objects in Java do not have an encoding. Though, that’s not accurate enough because it’s encoding is UTF-16, and it cannot be changed in any way.

2. Where is encoding then?

The only thing you can use is a byte[]. It doesn’t have any encoding but array PLUS encoding, can give you a string. In simple words: need the UTF-8 data? You need the byte[]! Let’s see how to do this:

First, we converted our String to byte[] using the getBytes() method which took one of the standard charsets as an argument. After that, we created another String object using UTF_8. This code will print:

 

Using switch on Strings in Java

In this post, we will learn something about using a switch on String in Java. The way you can do that depends on JDK level you are using.

1. JDK 6 or less

Switch statement works with byte, short, char and int primitive data types. It also works with enumerated types. But it doesn’t work with String. So, there are 2 ways to switch on Strings:

  1. If-then / if-then-else statement
    Output:
    In fact, that is not a switch statement, but it is work with Java 6 or less.
  2. Use enumerated types
    Enum class:
    Example code:
    Output:
    We are forced to use Enum if we want to use a switch statement.
  3. Switch on String directly?
    If we try to use a String directly, a program won’t compile because String is not a compatible type.

2. Since JDK 7

JDK7 introduces the ability to switch on Strings. This makes Java programmers life a bit easier. Nowadays, we can do it like that:

Output:

That’s all.

How to get current stack trace in Java

In general, we can get our stack trace by calling a method:

1. What a stack trace is?

The stack trace is a report of methods calls in our application. So in simple words: it can tell us where exactly our program is at the point of doing something. Sometimes it is needed when we need control while debugging our application. We can see where exactly an error occurs, where something when wrong and repair it quickly.

2. How to get a stack trace?

Let’s say our program has got main and three other methods. Each method calls next one in its body:

Now we want to see how our program goes through these methods. Using the function Thread.currentThread().getStackTrace() it’s very simple. We need to create the table of our stack elements to know WhereWeAre then display necessary information in a for loop.

Declaring table

After that, we will create a stack trace object to get the exact place in a loop:
Then, we can display needed information. The most important for us will be getMethodName() but we can add anything we want at this moment. For example, getFileName() or getLineNumber().
If we put this code in each method, we will always get current stack trace!
This code prints:

How to generate MD5 hash in Java

Today, we are going to learn how to generate MD5 hash. This algorithm is useful for verification e.g. files downloaded from the Internet or even hide our beloved password.

However, in this short tutorial, we will read up with the second option.

At the very beginning it is good to set our password:

After that, we can move to the most significant step. We need to tell our program which algorithm to choose. We will use the MessageDigest class.

As we should know, MD5 uses bytes to crypt the text, so we need to give him those. getBytes() and update() will be helpful here:

Now, we can let our algorithm finish the job using digest() method. It is important that the type of the new variable is byte[] (because it’s an array of bytes)

On this moment, our hash is ready. What we want to see is the result of our algorithm. This time, we need to convert array of bytes to integer so BigInteger is our friend:

If we get our conversion ready, we can convert our hash to String

The 16 number is there because we want to have the result in hex system. After all, the last thing to do is to show our new and fresh hash on the screen:

The output of the program will be:

 

Iterate through a HashMap in Java

In Java, we can iterate through a HashMap in few different ways.

First of all, we need to import required packages:

Then, naturally, set our HashMap and put some data in there:

1. Values and Keys

The simplest way to iterate is using keys or values.

Using values:

If we use keys the important thing is that we can find the values using only them by using get(key).  Although it is a slow and not efficient method. In this example we print keys and values both in one line:

 

2. Using Entry

Another possibility is using entry

Thanks to this package we can use the set of keys and values to iterate by both of them. Nowe we can use *.getKey() and *.getValue().

3. Iterator

In Java, we can use Iterator object to iterate through elements. The same we can do here.

Now, using the while loop we can easily iterate through a HashMap

Weak and soft reference differences in Java

The main difference between WeakReference and SoftReference is the moment of removal by a garbage collector.

1. WeakReference

WeakReference objects are always released when garbage collector reclaim.

The output of the above code always be:

2. SoftReference

As long as your program has a lot of unused memory, soft references will be kept in memory.

In above example, we don’t use all memory, so garbage collector doesn’t release softString.

SoftRefernece is good for a cache. When a program needs more memory SoftReference object will be removed.

How to iteratate over Enum in Java.

To iterate over enum, you have to use values() method.
When using values() method, you can iterate through enum as if it was an array.

In this example, I use this enum.

Java 7 or lower example

1. Get element by index.

2. Iterate using enhanced loop.

In the belove example dayOfTheWeek holds the current value of enum element.

Both programs prints:

Java 8 example.

In Java 8, we can use Arrays.stream and a lambda expression to iterate over enum.

 

Page 2 of 4

Privacy Preference Center

Necessary

Advertising

Analytics

Other