SoFunction
Updated on 2025-04-07

Java: Sample code for implementing collaborative filtering algorithm recommendation algorithm

1. What is collaborative filtering

Collaborative filtering is mainly divided into two types:

  • Collaborative filtering based on user: Recommend items based on similarities between users. For example, if the ratings of User A and User B are similar, then the items that User A likes may also be recommended to User B.
  • Collaborative filtering based on items: Recommended based on similarity between items. If the user gives a high rating for item X and item Y is similar to X, then item Y will be recommended to the user.

2. Data preparation

Before implementing collaborative filtering, we need to prepare a user-item rating matrix. Here is a simple example:

User/item Item 1 Item 2 Item 3 Item 4
User A 5 3 0 1
User B 4 0 0 1
User C 1 1 0 5
User D 0 0 5 4

In this matrix, 0 means that the user has no rating.

3. Implementation of collaborative filtering based on users

The following is a simple implementation of the user-based collaborative filtering algorithm:

3.1 Calculate similarity

We will use cosine similarity to calculate the similarity between users. The cosine similarity formula is:

cosine(A,B)=A⋅B∥A∥∥B∥\text{cosine}(A, B) = \frac{A \cdot B}{\|A\| \|B\|}cosine(A,B)=∥A∥∥B∥A⋅B​

3.2 Java implementation code

import ;
import ;
public class CollaborativeFiltering {
    // User rating matrix    private static final Map<String, Map<String, Integer>> ratings = new HashMap<>();
    static {
        ("UserA", ("Item1", 5, "Item2", 3, "Item4", 1));
        ("UserB", ("Item1", 4, "Item4", 1));
        ("UserC", ("Item2", 1, "Item4", 5));
        ("UserD", ("Item3", 5, "Item4", 4));
    }
    // Calculate cosine similarity    private double cosineSimilarity(Map<String, Integer> ratings1, Map<String, Integer> ratings2) {
        double dotProduct = 0.0;
        double normA = 0.0;
        double normB = 0.0;
        for (String item : ()) {
            if ((item)) {
                dotProduct += (item) * (item);
            }
            normA += ((item), 2);
        }
        for (double rating : ()) {
            normB += (rating, 2);
        }
        normA = (normA);
        normB = (normB);
        return (normA == 0 || normB == 0) ? 0 : dotProduct / (normA * normB);
    }
    // Recommend items for users    public Map<String, Double> recommendItems(String user) {
        Map<String, Integer> userRatings = (user);
        Map<String, Double> scoreMap = new HashMap<>();
        for (String otherUser : ()) {
            if (!(user)) {
                double similarity = cosineSimilarity(userRatings, (otherUser));
                for (String item : (otherUser).keySet()) {
                    if (!(item)) {
                        (item, (item, 0.0) + similarity * (otherUser).get(item));
                    }
                }
            }
        }
        return scoreMap;
    }
    public static void main(String[] args) {
        CollaborativeFiltering cf = new CollaborativeFiltering();
        Map<String, Double> recommendations = ("UserA");
        ("Recommended items to UserA: " + recommendations);
    }
}

Code explanation

  • User Rating Matrix: Use nestedMapTo store the user's ratings for items.
  • Cosine similarity calculation:passcosineSimilarityMethods calculate similarity between users.
  • Recommended items:existrecommendItemsIn the method, all users are traversed, similarity is calculated and unrated items are recommended for the target user.

4. Implementation of collaborative filtering based on items

Co-filtering based on items is similar to the user's implementation, but we need to first calculate the similarity between items.

4.1 Java implementation code

import ;
import ;
public class ItemBasedCollaborativeFiltering {
    private static final Map<String, Map<String, Integer>> ratings = new HashMap<>();
    static {
        ("UserA", ("Item1", 5, "Item2", 3, "Item4", 1));
        ("UserB", ("Item1", 4, "Item4", 1));
        ("UserC", ("Item2", 1, "Item4", 5));
        ("UserD", ("Item3", 5, "Item4", 4));
    }
    // Calculate the cosine similarity between items    private double cosineSimilarity(Map<String, Integer> item1, Map<String, Integer> item2) {
        // Similar to the user's calculation        // The specific implementation of similarity calculation is omitted        return 0.0; // Here you should return the actual calculated similarity    }
    // Recommend items for users    public Map<String, Double> recommendItems(String user) {
        Map<String, Integer> userRatings = (user);
        Map<String, Double> scoreMap = new HashMap<>();
        // Calculate similarity between items        // Implementation of omitted item similarity calculation and recommendation logic        return scoreMap;
    }
    public static void main(String[] args) {
        ItemBasedCollaborativeFiltering ibcf = new ItemBasedCollaborativeFiltering();
        Map<String, Double> recommendations = ("UserA");
        ("Recommended items to UserA: " + recommendations);
    }
}

Code explanation

  • The implementation logic based on the item is similar to that of the user, but the method of similarity calculation needs to be adjusted.
  • In the specific implementation, it is necessary to calculate the similarity of the item score and recommend similar items to the user.

5. Conclusion

Collaborative filtering algorithm is a powerful recommendation technology that can provide users with personalized recommendations based on their historical behavior and ratings. Implementing a collaborative filtering algorithm in Java requires processing of user rating data, calculating similarity, and generating recommended results. The above examples can help you understand how to implement a collaborative filtering recommendation system in a real project.

This is the end of this article about Java's recommendation algorithm for collaborative filtering algorithms. For more related contents of Java's recommendation algorithms, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!