Java 8 – How to get hashCode of a String ?

In this article, we will understand with a Java program on how to find hashCode of a String using Java 1.8 version

Already in one of the previous article, we discussed how to get hashCode of a String

Find hashCode of a String :

  • hashCode() method of String
    • This String method is used to get hash code of the invoking string
  • The hash code for a string object is computed as :- s[0]*31^(n-1) + s[1]*31^(n-2) + … + s[n-1] where,
    • s[i] –> is the ith character of the string
    • n –> is the length of the string
    • ^ –> indicates exponentiation
  • Note: The hash value of the empty string is zero (0)
  • Method signature :- public int hashCode();

GetStringHashCode.java

package in.bench.resources.java8.string.methods;

import java.util.Arrays;
import java.util.List;

public class GetStringHashCode {

	public static void main(String[] args) {

		// test strings
		List<String> fruits = Arrays.asList(
				"Apples",
				"Melons",
				"Mangoes",
				"Grapes",
				"Cherrys"
				);


		// get hashCode of each strings
		fruits
		.stream()
		.peek(s -> System.out.print(s + "\t"))
		.map(String::hashCode)
		.forEach(System.out::println);
	}
}

Output:

Apples	1967772793
Melons	-1993919424
Mangoes	-1794867248
Grapes	2140951720
Cherrys	-1887545894

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java 8 - How to get sub-string from a String ?
Java 8 - How to find First and Last index of particular character or sub-string in a String ?