| name | java-algorithm-patterns |
| description | 5 algorithm patterns with full Java implementations for common coding problems |
| version | 1.0.0 |
| category | toolchain |
| author | Claude MPM Team |
| license | MIT |
| progressive_disclosure | {"entry_point":{"summary":"Java algorithm patterns: Stream API, Binary Search, HashMap, Graph (JGraphT), Concurrent Collections","when_to_use":"When implementing algorithms, data structures, or solving coding problems in Java","quick_start":"Each pattern includes full implementation, complexity analysis, and key principles"}} |
| context_limit | 700 |
| tags | ["java","algorithms","stream-api","binary-search","hashmap","jgrapht","concurrent-collections","data-structures","complexity"] |
| requires_tools | [] |
Java Algorithm Patterns
Algorithm Patterns
1. Stream API Pattern (Functional Processing)
import java.util.*;
import java.util.stream.*;
public class StreamPatterns {
public static int lengthOfLongestSubstring(String s) {
if (s == null || s.isEmpty()) {
return 0;
}
Map<Character, Integer> charIndex = new HashMap<>();
int maxLength = 0;
int left = 0;
for (int right = 0; right < s.length(); right++) {
char c = s.charAt(right);
if (charIndex.containsKey(c) && charIndex.get(c) >= left) {
left = charIndex.get(c) + 1;
}
charIndex.put(c, right);
maxLength = Math.max(maxLength, right - left + 1);
}
return maxLength;
}
public static Map<String, Long> countFrequencies(List<String> items) {
return items.stream()
.collect(Collectors.groupingBy(
item -> item,
Collectors.counting()
));
}
}
2. Binary Search Pattern
public class BinarySearchPatterns {
public static double findMedianSortedArrays(int[] nums1, int[] nums2) {
if (nums1.length > nums2.length) {
return findMedianSortedArrays(nums2, nums1);
}
int m = nums1.length;
int n = nums2.length;
int left = 0;
int right = m;
while (left <= right) {
int partition1 = (left + right) / 2;
int partition2 = (m + n + 1) / 2 - partition1;
int maxLeft1 = (partition1 == 0) ? Integer.MIN_VALUE : nums1[partition1 - 1];
int minRight1 = (partition1 == m) ? Integer.MAX_VALUE : nums1[partition1];
int maxLeft2 = (partition2 == 0) ? Integer.MIN_VALUE : nums2[partition2 - 1];
int minRight2 = (partition2 == n) ? Integer.MAX_VALUE : nums2[partition2];
if (maxLeft1 <= minRight2 && maxLeft2 <= minRight1) {
if ((m + n) % 2 == 0) {
return (Math.max(maxLeft1, maxLeft2) + Math.min(minRight1, minRight2)) / 2.0;
}
return Math.max(maxLeft1, maxLeft2);
} else if (maxLeft1 > minRight2) {
right = partition1 - 1;
} else {
left = partition1 + 1;
}
}
throw new IllegalArgumentException("Input arrays must be sorted");
}
}
3. HashMap Pattern (O(1) Lookup)
import java.util.*;
public class HashMapPatterns {
public static int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> seen = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (seen.containsKey(complement)) {
return new int[] { seen.get(complement), i };
}
seen.put(nums[i], i);
}
return new int[] {};
}
}
4. Graph Algorithms (JGraphT)
import org.jgrapht.*;
import org.jgrapht.alg.shortestpath.*;
import org.jgrapht.graph.*;
import java.util.*;
public class GraphPatterns {
public static List<String> findShortestPath(
Graph<String, DefaultWeightedEdge> graph,
String source,
String target
) {
DijkstraShortestPath<String, DefaultWeightedEdge> dijkstra =
new DijkstraShortestPath<>(graph);
GraphPath<String, DefaultWeightedEdge> path = dijkstra.getPath(source, target);
return path != null ? path.getVertexList() : Collections.emptyList();
}
public static Graph<String, DefaultWeightedEdge> createGraph() {
Graph<String, DefaultWeightedEdge> graph =
new DefaultDirectedWeightedGraph<>(DefaultWeightedEdge.class);
graph.addVertex("A");
graph.addVertex("B");
graph.addVertex("C");
DefaultWeightedEdge edge = graph.addEdge("A", "B");
graph.setEdgeWeight(edge, 5.0);
return graph;
}
}
5. Concurrent Collections Pattern
import java.util.concurrent.*;
import java.util.*;
public class ConcurrentPatterns {
public static class ProducerConsumer {
private final BlockingQueue<String> queue = new LinkedBlockingQueue<>(100);
public void produce(String item) throws InterruptedException {
queue.put(item);
}
public String consume() throws InterruptedException {
return queue.take();
}
}
public static class ConcurrentCache {
private final ConcurrentHashMap<String, String> cache = new ConcurrentHashMap<>();
public String getOrCompute(String key) {
return cache.computeIfAbsent(key, k -> expensiveComputation(k));
}
private String expensiveComputation(String key) {
return "computed_" + key;
}
}
}