How to detect the language of a string in Java
2 min readNov 26, 2019
Today we shall look at how to implement language detection quickly and easily using a Cloudmersive API. Let’s get started.
The library we will be using must be compiled dynamically with Jitpack. So we will first set up our references in Maven POM.
Repository:
<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
Dependency:
<dependencies>
<dependency>
<groupId>com.github.Cloudmersive</groupId>
<artifactId>Cloudmersive.APIClient.Java</artifactId>
<version>v2.32</version>
</dependency>
</dependencies>
Now we just have to call languageDetectionPost:
// Import classes:
//import com.cloudmersive.client.invoker.ApiClient;
//import com.cloudmersive.client.invoker.ApiException;
//import com.cloudmersive.client.invoker.Configuration;
//import com.cloudmersive.client.invoker.auth.*;
//import com.cloudmersive.client.LanguageDetectionApi;ApiClient defaultClient = Configuration.getDefaultApiClient();// Configure API key authorization: Apikey
ApiKeyAuth Apikey = (ApiKeyAuth) defaultClient.getAuthentication("Apikey");
Apikey.setApiKey("YOUR API KEY");
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//Apikey.setApiKeyPrefix("Token");LanguageDetectionApi apiInstance = new LanguageDetectionApi();
String textToDetect = "textToDetect_example"; // String | Text to detect language of
try {
LanguageDetectionResponse result = apiInstance.languageDetectionPost(textToDetect);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling LanguageDetectionApi#languageDetectionPost");
e.printStackTrace();
}
And that’s all there is to it. Let’s look at an example with the input string “gemutlicheit.” Our output:
{
"Successful": true,
"DetectedLanguage_ThreeLetterCode": "DEU",
"DetectedLanguage_FullName": "German"
}
As you can see we are told whether the function was successful, the full name of the language, and a three letter code for the language.