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:
- Java 8 – How to get a specific character from String ?
- Java 8 – How to check whether particular word/letter/sub-string is present in the String ?
- Java 8 – How to check whether particular String endsWith specific word/letter ?
- Java 8 – How to check whether particular String startsWith specific word/letter ?
- Java 8 – How to check whether a String is empty or not ?
- Java 8 – How to get length of a String ?
- Java 8 – How to convert a String into char[] Arrays ?
- Java 8 – How to convert a String into UpperCase String ?
- Java 8 – How to convert a String into LowerCase String ?
- Java 8 – How to remove leading and trailing whitespaces in a String ?
- Java 8 – How to replace a String with another String ?
- Java 8 – How to split a String based on delimiter ?
- Java 8 – How to convert primitive data-types into String ?
- Java 8 – How to join String[] Arrays elements using different delimiter ?
- Java 8 – How to join List of String elements using different delimiter ?
- Java 8 – How to find 1st and last index of particular character/substring in a String ?
- Java 8 – How to get hashCode of a String ?
- Java 8 – How to get sub-string from a String ?
References:
- https://docs.oracle.com/javase/8/docs/api/java/lang/String.html
- https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html
Happy Coding !!
Happy Learning !!