Java
Sentiment Analysis
Programming
Library
Natural Language Processing

Sentiment Analysis java Library

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

Introduction

Sentiment analysis is the process of determining whether a piece of text expresses a positive, negative, or neutral opinion. It is widely used in customer feedback analysis, social media monitoring, and market research. Java developers have access to several mature libraries that handle sentiment analysis, ranging from rule-based pipelines to deep learning frameworks. This article covers the most practical Java libraries for sentiment analysis, with setup instructions and code examples for each.

Stanford CoreNLP

Stanford CoreNLP is the most established NLP library in the Java ecosystem. It provides a full linguistic analysis pipeline that includes tokenization, part-of-speech tagging, named entity recognition, and sentiment analysis.

How It Works

CoreNLP's sentiment module uses a recursive neural tensor network trained on the Stanford Sentiment Treebank. It classifies text into five levels: Very Negative, Negative, Neutral, Positive, and Very Positive. The model analyzes the parse tree of each sentence, assigning sentiment scores to phrases and composing them up to the root.

Setup with Maven

xml
1<dependency>
2    <groupId>edu.stanford.nlp</groupId>
3    <artifactId>stanford-corenlp</artifactId>
4    <version>4.5.6</version>
5</dependency>
6<dependency>
7    <groupId>edu.stanford.nlp</groupId>
8    <artifactId>stanford-corenlp</artifactId>
9    <version>4.5.6</version>
10    <classifier>models</classifier>
11</dependency>

Code Example

java
1import edu.stanford.nlp.pipeline.*;
2import edu.stanford.nlp.ling.*;
3import edu.stanford.nlp.sentiment.SentimentCoreAnnotations;
4import java.util.Properties;
5
6public class SentimentExample {
7    public static void main(String[] args) {
8        Properties props = new Properties();
9        props.setProperty("annotators", "tokenize,ssplit,pos,parse,sentiment");
10
11        StanfordCoreNLP pipeline = new StanfordCoreNLP(props);
12        String text = "The product quality is excellent and delivery was fast.";
13
14        CoreDocument doc = new CoreDocument(text);
15        pipeline.annotate(doc);
16
17        for (CoreSentence sentence : doc.sentences()) {
18            String sentiment = sentence.sentiment();
19            System.out.println("Text: " + sentence.text());
20            System.out.println("Sentiment: " + sentiment);
21        }
22    }
23}

CoreNLP is heavy on resources. The models download is several hundred megabytes, and loading the pipeline takes a few seconds. For production use, initialize the pipeline once and reuse it across requests.

Apache OpenNLP

Apache OpenNLP provides machine learning tools for NLP tasks including tokenization, sentence detection, and document classification. It does not ship a pre-trained sentiment model, but you can train one using its DocumentCategorizerME component.

Training a Sentiment Model

java
1import opennlp.tools.doccat.*;
2import opennlp.tools.util.*;
3import java.io.*;
4
5public class TrainSentiment {
6    public static void main(String[] args) throws Exception {
7        InputStreamFactory dataIn = new MarkableFileInputStreamFactory(
8            new File("sentiment-training.txt")
9        );
10
11        ObjectStream<String> lineStream = new PlainTextByLineStream(dataIn, "UTF-8");
12        ObjectStream<DocumentSample> sampleStream = new DocumentSampleStream(lineStream);
13
14        DoccatFactory factory = new DoccatFactory();
15        TrainingParameters params = TrainingParameters.defaultParams();
16        params.put(TrainingParameters.CUTOFF_PARAM, "2");
17        params.put(TrainingParameters.ITERATIONS_PARAM, "100");
18
19        DoccatModel model = DocumentCategorizerME.train("en", sampleStream, params, factory);
20
21        DocumentCategorizerME categorizer = new DocumentCategorizerME(model);
22        double[] outcomes = categorizer.categorize(new String[]{"Great", "service"});
23        String category = categorizer.getBestCategory(outcomes);
24        System.out.println("Predicted sentiment: " + category);
25    }
26}

The training data file uses a simple format where each line starts with the category label followed by the tokenized text. OpenNLP is lighter than CoreNLP but requires you to supply your own labeled training data.

DeepLearning4j (DL4J)

For developers who need deep learning capabilities, DL4J is a Java-native neural network framework. It supports LSTM and CNN architectures that are commonly used for sentiment classification on longer documents.

Setup with Maven

xml
1<dependency>
2    <groupId>org.deeplearning4j</groupId>
3    <artifactId>deeplearning4j-core</artifactId>
4    <version>1.0.0-M2.1</version>
5</dependency>
6<dependency>
7    <groupId>org.nd4j</groupId>
8    <artifactId>nd4j-native-platform</artifactId>
9    <version>1.0.0-M2.1</version>
10</dependency>

DL4J is best suited when you have a large labeled dataset and need to train a custom model with higher accuracy than what rule-based or traditional ML approaches provide. The tradeoff is significantly more setup and training time.

Choosing the Right Library

The right choice depends on your project requirements.

Stanford CoreNLP is ideal when you need a ready-to-use sentiment model with no training step. It handles English text well out of the box and provides sentence-level sentiment with five granularity levels.

Apache OpenNLP works best when you have domain-specific training data and want a lightweight, customizable classifier. It gives you full control over the categories and training process.

DL4J is appropriate for teams that need state-of-the-art accuracy on large datasets and are comfortable building and training neural network models in Java.

Common Pitfalls

  1. Ignoring model size and startup cost. CoreNLP models are large and take several seconds to load. If you are building a serverless function or a CLI tool, this cold-start penalty can be significant. Load the pipeline once and reuse it.
  2. Not preprocessing text. Raw text with HTML tags, URLs, or excessive punctuation degrades accuracy for all libraries. Clean and normalize input before feeding it to the model.
  3. Assuming English-only. Most pre-trained models are English-centric. If your application processes multiple languages, verify that the library and model support your target languages, or train separate models.
  4. Treating sentiment as binary. Real-world text often contains mixed sentiment (positive about one aspect, negative about another). Consider aspect-based sentiment analysis or sentence-level analysis instead of a single document score.
  5. Overcomplicating simple tasks. If you just need positive, negative, or neutral classification for short texts like product reviews, CoreNLP's built-in model is usually sufficient. Reaching for DL4J adds complexity that may not be justified.

Summary

Java provides several strong options for sentiment analysis. Stanford CoreNLP offers a production-ready pipeline with five sentiment levels. Apache OpenNLP gives you a lightweight framework for training custom classifiers. DL4J supports deep learning approaches for maximum accuracy on large datasets. Start with CoreNLP for general use cases, move to OpenNLP if you need domain-specific models, and choose DL4J when accuracy on large corpora justifies the additional infrastructure.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

All Rights Reserved.