Search⌘ K
AI Features

Solution: The Fraud Detection Ring

Explore how to solve a fraud detection problem by leveraging the Java Collections framework. Understand reading CSV data into lists, parsing and storing user-device relationships with maps and sets, and efficiently identifying users exceeding device limits. Gain practical skills in managing and analyzing data using Java's core collection classes.

We'll cover the following...
Java 25
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.List;
public class SecurityScanner {
public static Map<Integer, Set<String>> loadUserDevices(String filePath) {
Map<Integer, Set<String>> userMap = new HashMap<>();
try {
List<String> lines = Files.readAllLines(Path.of(filePath));
// Start at 1 to skip header
for (int i = 1; i < lines.size(); i++) {
String[] parts = lines.get(i).split(",");
// Parse CSV columns
int userId = Integer.parseInt(parts[0].trim());
String device = parts[1].trim();
// Ensure the Set exists for this user
userMap.putIfAbsent(userId, new HashSet<>());
// Add the device (Set handles uniqueness automatically)
userMap.get(userId).add(device);
}
} catch (IOException e) {
System.out.println("Error reading file: " + e.getMessage());
}
return userMap;
}
public static Set<Integer> identifySuspiciousUsers(Map<Integer, Set<String>> userDeviceMap, int limit) {
Set<Integer> suspiciousUsers = new HashSet<>();
for (Map.Entry<Integer, Set<String>> entry : userDeviceMap.entrySet()) {
Integer userId = entry.getKey();
Set<String> devices = entry.getValue();
// Check if unique device count exceeds the limit
if (devices.size() > limit) {
suspiciousUsers.add(userId);
}
}
return suspiciousUsers;
}
public static void main(String[] args) {
System.out.println("Scanning logs...");
Map<Integer, Set<String>> data = loadUserDevices("log.csv");
System.out.println("Total Users Found: " + data.size());
System.out.println("--- Device Counts ---");
for (Integer user : data.keySet()) {
System.out.println(" - User " + user + ": " + data.get(user).size() + " unique devices");
}
System.out.println("\n--- DETECTING THREATS (Limit: 3) ---");
Set<Integer> flagged = identifySuspiciousUsers(data, 3);
if (flagged.isEmpty()) {
System.out.println("No suspicious activity detected.");
} else {
System.out.println("Flagged Users: " + flagged);
}
}
}
...