Java
javaTutorial
Implementing Tic-Tac-Toe victory condition detection using Java Streams and hybrid programming
Implementing Tic-Tac-Toe victory condition detection using Java Streams and hybrid programming

This article explores how to use Java Streams combined with hybrid programming strategies to efficiently detect victory conditions in the Tic-Tac-Toe game. In response to the challenge that it is difficult to handle complex spatial logic purely using the Stream API, the article proposes a method by defining neighbor offsets, combining `Stream.anyMatch()` and local imperative logic. This solution can accurately determine whether the player's latest move forms a horizontal, vertical or diagonal winning combination, avoids unnecessary global traversal, and improves detection efficiency.
The Challenge of Tic-Tac-Toe Victory Condition Detection
In the game of Tic-Tac-Toe, the key to determining whether one side is winning or not is to check whether there is a straight line of three consecutive pieces on the board composed of the same player's pieces. This includes horizontal, vertical and two diagonal lines. Beginners often try to use Java Streams' aggregation functions (such as Collections.frequency or groupingBy) to detect whether there are three identical values on the board. However, this approach is fundamentally flawed: just having three identical values doesn't mean they form a winning line. For example, there may be three 'X's scattered across the board, but they are not connected in a line. Therefore, simple counting or grouping operations cannot satisfy the victory judgment logic of Tic-Tac-Toe.
Relying purely on Java Streams to handle this kind of complex logic that needs to consider spatial location relationships will become extremely complex and difficult to maintain. The Stream API is good at data conversion, filtering, and aggregation. However, for scenarios that require frequent access to adjacent elements, boundary checks, and multi-step conditional judgments, its expressive capabilities are limited. It often requires the introduction of a large number of intermediate operations and state management, which in turn reduces the readability and efficiency of the code.
Hybrid programming solution: combination of Stream and imperative logic
In order to effectively solve the problem of victory condition detection in Tic-Tac-Toe while taking advantage of the simplicity of Java Streams as much as possible, we can adopt a hybrid programming strategy. The core idea is to use the Stream API to traverse potential winning combination patterns, and encapsulate specific logic involving spatial position judgment in functions or predicates that are more suitable for the imperative style.
This approach avoids unnecessary global scans of the entire board and instead focuses on examining potential winning lines associated with the latest moves.
1. Checkerboard representation and neighbor offset definition
First, we need a clear representation of the chessboard, usually using a two-dimensional list or array. To facilitate calculation, we can pre-define neighbor offsets representing various winning directions (horizontal, vertical, diagonal). These offsets will help us expand from a center point (the latest drop position) to both sides to check if a straight line is formed.
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Stream;
public class TicTacToe {
// Define neighbor offsets for all possible winning combination directions // Each internal array represents a direction (e.g. horizontal, vertical, diagonal)
//Each direction contains two offsets, pointing to the left/right/up/down/diagonal directions of the center point respectively public static final int[][][] NEIGHBOURS = {
{{0, -1}, {0, 1}}, // Horizontal direction: left, right {{-1, 0}, {1, 0}}, // Vertical direction: up, down {{-1, -1}, {1, 1}}, // Main diagonal: upper left, lower right {{1, -1}, {-1, 1}} // Anti-diagonal: lower left, upper right};
// Checkerboard representation, use List<list>> to facilitate modification of elements // Note: The list created by Arrays.asList() is of fixed size, but its elements are allowed to be modified private List<list>> board = List.of(
Arrays.asList("1", "4", "7"), // The initial value can be any non-null value Arrays.asList("2", "5", "8"),
Arrays.asList("3", "6", "9")
);
// ...other methods...
}</list></list>
2. Safely obtain the board value
When checking neighbors, boundary cases must be handled to prevent out-of-bounds access. The getBoardValue method provides a safe access interface and returns a special value when the coordinates are invalid, ensuring that subsequent comparisons will not throw exceptions and can correctly determine a non-winning combination.
/**
* Safely obtain the value of the specified position on the chessboard.
* Handle out-of-bounds situations to avoid ArrayIndexOutOfBoundsException.
*
* @param row row index * @param col column index * @return value on the chessboard, if the index is invalid, return "INVALID INDEX"
*/
public String getBoardValue(int row, int col) {
if (row = board.size() || col = board.get(row).size()) {
return "INVALID INDEX"; // Return an illegal value, ensure that isWinningCombination will return false
}
return board.get(row).get(col);
}
3. Check for a specific combination of predicates
The isWinningCombination method returns a Predicate
/**
* Generate a predicate that checks whether a move for a given row and column wins in a specific combination of neighbors.
*
* @param row The row index of the player's latest move * @param col The column index of the player's latest move * @return A Predicate that accepts a two-dimensional array representing neighbor offsets and determines whether a winning combination is formed */
public Predicate<int> isWinningCombination(int row, int col) {
return neighbor -> {
int[] leftShift = neighbor[0]; // The offset of the first neighbor int[] rightShift = neighbor[1]; // The offset of the second neighbor String currentPlayer = getBoardValue(row, col); // The player with the latest move // Check if the first neighbor is the same as the current player boolean isLeftNeighborSame = getBoardValue(row leftShift[0], col leftShift[1])
.equals(currentPlayer);
// Check if the second neighbor is the same as the current player boolean isRightNeighborSame = getBoardValue(row rightShift[0], col rightShift[1])
.equals(currentPlayer);
// If both neighbors are the same as the current player, a winning combination is formed return isLeftNeighborSame && isRightNeighborSame;
};
}</int>
4. Determine whether it is a winning move
isWinningMove is the entry point of the entire logic. It uses Stream.anyMatch() to traverse all winning directions defined in the NEIGHBOURS array. As long as one direction satisfies the isWinningCombination predicate, it means that the current move leads to victory.
/**
* Determine whether the player's move at a given position is a winning shot.
*
* @param row The row index of the player's latest move * @param col The column index of the player's latest move * @return If the move constitutes a winning combination, return true; otherwise, return false.
*/
public boolean isWinningMove(int row, int col) {
// Use Stream.anyMatch() to traverse all predefined neighbor combinations // As long as there is a combination that meets the conditions of isWinningCombination, it means winning return Arrays.stream(NEIGHBOURS)
.anyMatch(isWinningCombination(row, col));
}
Complete sample code
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Stream;
public class TicTacToe {
// Define neighbor offsets for all possible winning combination directions // Each internal array represents a direction (e.g. horizontal, vertical, diagonal)
//Each direction contains two offsets, pointing to the left/right/up/down/diagonal directions of the center point respectively public static final int[][][] NEIGHBOURS = {
{{0, -1}, {0, 1}}, // Horizontal direction: left, right {{-1, 0}, {1, 0}}, // Vertical direction: up, down {{-1, -1}, {1, 1}}, // Main diagonal: upper left, lower right {{1, -1}, {-1, 1}} // Anti-diagonal: lower left, upper right};
// Checkerboard representation, use List> to facilitate modification of elements // Note: The list created by Arrays.asList() is of fixed size, but its elements are allowed to be modified private List> board = List.of(
Arrays.asList("1", "4", "7"), // The initial value can be any non-null value Arrays.asList("2", "5", "8"),
Arrays.asList("3", "6", "9")
);
/**
* Determine whether the player's move at a given position is a winning shot.
*
* @param row The row index of the player's latest move * @param col The column index of the player's latest move * @return If the move constitutes a winning combination, return true; otherwise, return false.
*/
public boolean isWinningMove(int row, int col) {
// Use Stream.anyMatch() to traverse all predefined neighbor combinations // As long as there is a combination that meets the conditions of isWinningCombination, it means winning return Arrays.stream(NEIGHBOURS)
.anyMatch(isWinningCombination(row, col));
}
/**
* Generate a predicate that checks whether a move for a given row and column wins in a specific combination of neighbors.
*
* @param row The row index of the player's latest move * @param col The column index of the player's latest move * @return A Predicate that accepts a two-dimensional array representing neighbor offsets and determines whether a winning combination is formed */
public Predicate isWinningCombination(int row, int col) {
return neighbor -> {
int[] leftShift = neighbor[0]; // The offset of the first neighbor int[] rightShift = neighbor[1]; // The offset of the second neighbor String currentPlayer = getBoardValue(row, col); // The player with the latest move // Check if the first neighbor is the same as the current player boolean isLeftNeighborSame = getBoardValue(row leftShift[0], col leftShift[1])
.equals(currentPlayer);
// Check if the second neighbor is the same as the current player boolean isRightNeighborSame = getBoardValue(row rightShift[0], col rightShift[1])
.equals(currentPlayer);
// If both neighbors are the same as the current player, a winning combination is formed return isLeftNeighborSame && isRightNeighborSame;
};
}
/**
* Safely obtain the value of the specified position on the chessboard.
* Handle out-of-bounds situations to avoid ArrayIndexOutOfBoundsException.
*
* @param row row index * @param col column index * @return value on the chessboard, if the index is invalid, return "INVALID INDEX"
*/
public String getBoardValue(int row, int col) {
if (row = board.size() || col = board.get(row).size()) {
return "INVALID INDEX"; // Return an illegal value, ensure that isWinningCombination will return false
}
return board.get(row).get(col);
}
// Example: Update the board and check for victory public void makeMove(int row, int col, String player) {
if (row >= 0 && row = 0 && col System.out.println(String.join(" ", r)));
if (isWinningMove(row, col)) {
System.out.println("player" player "win!");
} else {
System.out.println("Game continues.");
}
} else {
System.out.println("Invalid position.");
}
}
public static void main(String[] args) {
TicTacToe game = new TicTacToe();
// Simulate the game process // Player X moves game.makeMove(0, 0, "X"); // 1
game.makeMove(1, 0, "O"); // 4
game.makeMove(0, 1, "X"); // 2
game.makeMove(1, 1, "O"); // 5
game.makeMove(0, 2, "X"); // 3 -> Player X wins at level}
}
Notes and Summary
- The necessity of hybrid programming: This solution is not completely purely functional, but cleverly combines the declarative style of Java Streams (anyMatch) and imperative logic (boundary checking in getBoardValue and specific value comparison in isWinningCombination). For scenarios that require complex spatial or state judgments, this hybrid approach is often a more practical and efficient choice.
- Efficiency optimization: This method only checks the potential winning lines adjacent to the latest move, rather than traversing all possible combinations of the entire chessboard, which greatly improves detection efficiency.
- Readability: By defining neighbor offsets as constants and encapsulating specific checking logic in predicates, the code structure is clear and easy to understand and maintain.
- Board mutability: The example uses Arrays.asList to create an inner list, which allows modification of elements in the list (such as setting a player's pieces), but the list created by outer List.of is immutable and does not allow rows to be added or removed. In a real game, it is crucial to ensure that the board state is updated correctly.
- Scalability: If you need to support chessboards of different sizes, just adjust the definition of the NEIGHBOURS array and ensure that the bounds checking logic of getBoardValue can adapt to the new chessboard size.
Through the above hybrid programming strategy, we can elegantly and efficiently implement the victory condition detection of Tic-Tac-Toe, making full use of the advantages of Java Streams while avoiding its limitations in processing complex spatial logic. This method is not only applicable to tic-tac-toe, but also provides a useful reference for victory judgment in other similar board games.
The above is the detailed content of Implementing Tic-Tac-Toe victory condition detection using Java Streams and hybrid programming. For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undress AI Tool
Undress images for free
AI Clothes Remover
Online AI tool for removing clothes from photos.
Undresser.AI Undress
AI-powered app for creating realistic nude photos
ArtGPT
AI image generator for creative art from text prompts.
Stock Market GPT
AI powered investment research for smarter decisions
Hot Article
Popular tool
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
20518
7
13631
4
How to configure Spark distributed computing environment in Java_Java big data processing
Mar 09, 2026 pm 08:45 PM
Spark cannot run in local mode, ClassNotFoundException: org.apache.spark.sql.SparkSession. This is the most common first step of getting stuck: even the dependencies are not correct. Only spark-core_2.12 is written in Maven, but spark-sql_2.12 is not added. SparkSession crashes as soon as it is built. The Scala version must strictly match the official Spark compiled version - Spark3.4.x uses Scala2.12 by default. If you use spark-sqljar of 2.13, the class loader cannot directly find the main class. Practical advice: Go to mvnre
How to safely map user-entered weekday string to integer value and implement date offset operation in Java
Mar 09, 2026 pm 09:43 PM
This article introduces a concise and maintainable way to map the weekday string (such as "Monday") to the corresponding serial number (1-7), and use the modulo operation to realize the forward and backward offset of any number of days (such as Monday plus 4 days to get Friday), avoiding lengthy if chains and hard-coded logic.
How to generate a list of duplicate elements using Java's Collections.nCopies_Initialization tips
Mar 06, 2026 am 06:24 AM
Collections.nCopies returns an immutable view. Calling add/remove will throw UnsupportedOperationException; it needs to be wrapped with newArrayList() to modify it, and it is disabled for mutable objects.
What is exception masking (Suppressed Exceptions) in Java_Multiple resource shutdown exception handling
Mar 10, 2026 pm 06:57 PM
What is SuppressedException: It is not "swallowed", but actively archived by the JVM. SuppressedException is not an exception loss, but the JVM quietly attaches the secondary exception to the main exception under the premise that "only one exception must be thrown" for you to verify afterwards. It is automatically triggered by the JVM in only two scenarios: one is that the resource closure in try-with-resources fails, and the other is that you manually call addSuppressed() in finally. The key difference is: the former is fully automatic and safe; the latter requires you to keep it to yourself, and it can be written as shadowing if you are not careful. try-
How to use Homebrew to install Java on Mac_A must-have Java tool chain for developers
Mar 09, 2026 pm 09:48 PM
Homebrew installs the latest stable version of openjdk (such as JDK22) by default, not the LTS version; you need to explicitly execute brewinstallopenjdk@17 or brewinstallopenjdk@21 to install the LTS version, and manually configure PATH and JAVA_HOME to be correctly recognized by the system and IDE.
How to correctly implement runtime file writing in Java applications (avoiding JAR internal write failures)
Mar 09, 2026 pm 07:57 PM
After a Java application is packaged as a JAR, data cannot be written directly to the resources in the JAR package (such as test.txt) because the JAR is essentially a read-only ZIP archive; the correct approach is to write variable data to an external path (such as a user directory, a temporary directory, or a configuration-specified path).
What is the underlying principle of array expansion in Java_Java memory dynamic adjustment analysis
Mar 09, 2026 pm 09:45 PM
ArrayList.add() triggers expansion because grow() is called when size is equal to elementData.length. The first add allocates 10 capacity, and subsequent expansion is 1.5 times and not less than the minimum requirement, relying on delayed initialization and System.arraycopy optimization.
How to safely read a line of integer input in Java and avoid Scanner blocking
Mar 06, 2026 am 06:21 AM
This article introduces typical blocking problems when using Scanner to read multiple integers in a single line. It points out that hasNextInt() will wait indefinitely when there is no subsequent input, and recommends a safe alternative with nextLine() string splitting as the core.





