上一篇
java搜索功能怎么实现
- 后端开发
- 2025-07-30
- 4
Java中实现搜索功能,通常可借助集合类的
contains
方法或遍历集合元素进行匹配。
Java中实现搜索功能有多种方式,具体取决于搜索的场景和需求,以下是几种常见的实现方式及其详细步骤:
基本字符串搜索
使用indexOf
方法
Java的String
类提供了indexOf
方法,可以用于查找子字符串在父字符串中的位置。
public class StringSearch { public static void main(String[] args) { String text = "Hello, this is a sample text for searching."; String keyword = "sample"; int index = text.indexOf(keyword); if (index != -1) { System.out.println("Keyword found at index: " + index); } else { System.out.println("Keyword not found."); } } }
使用正则表达式
正则表达式可以用于更复杂的搜索模式。
import java.util.regex.; public class RegexSearch { public static void main(String[] args) { String text = "Hello, this is a sample text for searching."; String pattern = "sample"; Pattern compiledPattern = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE); Matcher matcher = compiledPattern.matcher(text); if (matcher.find()) { System.out.println("Keyword found at index: " + matcher.start()); } else { System.out.println("Keyword not found."); } } }
在集合中搜索
在List
中搜索
可以使用contains
方法或者遍历列表来查找元素。
import java.util.ArrayList; import java.util.List; public class ListSearch { public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("apple"); list.add("banana"); list.add("cherry"); String keyword = "banana"; if (list.contains(keyword)) { System.out.println("Keyword found in the list."); } else { System.out.println("Keyword not found in the list."); } } }
在Map
中搜索
可以通过键或值来查找。
import java.util.HashMap; import java.util.Map; public class MapSearch { public static void main(String[] args) { Map<String, String> map = new HashMap<>(); map.put("1", "apple"); map.put("2", "banana"); map.put("3", "cherry"); String key = "2"; String value = "banana"; if (map.containsKey(key)) { System.out.println("Key found with value: " + map.get(key)); } else { System.out.println("Key not found."); } boolean found = false; for (Map.Entry<String, String> entry : map.entrySet()) { if (entry.getValue().equals(value)) { found = true; System.out.println("Value found with key: " + entry.getKey()); break; } } if (!found) { System.out.println("Value not found."); } } }
在数据库中搜索
使用JDBC
通过JDBC连接数据库并执行SQL查询。
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class DatabaseSearch { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/mydatabase"; String user = "root"; String password = "password"; try { Connection connection = DriverManager.getConnection(url, user, password); Statement statement = connection.createStatement(); String query = "SELECT FROM users WHERE name = 'John Doe'"; ResultSet resultSet = statement.executeQuery(query); while (resultSet.next()) { System.out.println("User found: " + resultSet.getString("name")); } connection.close(); } catch (Exception e) { e.printStackTrace(); } } }
使用ORM框架(如Hibernate)
通过Hibernate等ORM框架可以更方便地进行数据库操作。
import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.query.Query; import java.util.List; public class HibernateSearch { public static void main(String[] args) { SessionFactory factory = new Configuration().configure().buildSessionFactory(); Session session = factory.openSession(); String keyword = "John Doe"; Query<User> query = session.createQuery("FROM User WHERE name = :name", User.class); query.setParameter("name", keyword); List<User> users = query.list(); for (User user : users) { System.out.println("User found: " + user.getName()); } session.close(); factory.close(); } }
全文搜索(Lucene)
Apache Lucene是一个强大的全文搜索库,适用于复杂的搜索需求。
import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.TextField; import org.apache.lucene.index.; import org.apache.lucene.queryparser.classic.QueryParser; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.TopDocs; import org.apache.lucene.store.Directory; import org.apache.lucene.store.RAMDirectory; public class LuceneSearch { public static void main(String[] args) throws Exception { // Create a RAM directory for the index Directory index = new RAMDirectory(); // Create an index writer and add documents to the index IndexWriterConfig config = new IndexWriterConfig(new StandardAnalyzer()); IndexWriter writer = new IndexWriter(index, config); addDoc(writer, "Lucene in Action", "193688177"); addDoc(writer, "Lucene for Dummies", "55320155"); addDoc(writer, "Managing Gigabytes", "59319340"); writer.close(); // Now search the index for the term "Lucene" DirectoryReader reader = DirectoryReader.open(index); IndexSearcher searcher = new IndexSearcher(reader); QueryParser parser = new QueryParser("title", new StandardAnalyzer()); Query query = parser.parse("Lucene"); TopDocs results = searcher.search(query, 10); System.out.println("Found " + results.totalHits + " hits."); for (int i = 0; i < results.scoreDocs.length; i++) { Document doc = results.scoreDocs[i].doc; System.out.println((i + 1) + ". " + doc.get("title") + "t" + doc.get("isbn")); } } private static void addDoc(IndexWriter w, String title, String isbn) throws Exception { Document doc = new Document(); doc.add(new TextField("title", title, Field.Store.YES)); doc.add(new TextField("isbn", isbn, Field.Store.YES)); w.addDocument(doc); } }
在文件中搜索
逐行读取文件并搜索关键词
可以使用BufferedReader
逐行读取文件并查找关键词。
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class FileSearch { public static void main(String[] args) { String filePath = "path/to/your/file.txt"; String keyword = "searchTerm"; try (BufferedReader br = new BufferedReader(new FileReader(filePath))) { String line; int lineNumber = 0; while ((line = br.readLine()) != null) { lineNumber++; if (line.contains(keyword)) { System.out.println("Keyword found at line " + lineNumber + ": " + line); } } } catch (IOException e) { e.printStackTrace(); } } }
高级搜索算法(如二分查找、深度优先搜索等)
二分查找(适用于有序数组)
二分查找是一种高效的搜索算法,适用于有序数组。
import java.util.Arrays; public class BinarySearch { public static void main(String[] args) { int[] array = {1, 3, 5, 7, 9, 11, 13, 15}; int target = 7; int index = Arrays.binarySearch(array, target); if (index >= 0) { System.out.println("Target found at index: " + index); } else { System.out.println("Target not found."); } } }
深度优先搜索(DFS)用于图或树结构中的搜索
DFS是一种用于遍历或搜索树或图的算法,以下是一个在图中搜索节点的示例。
import java.util.; public class GraphSearch { private static Map<String, List<String>> graph = new HashMap<>(); private static Set<String> visited = new HashSet<>(); private static Deque<String> stack = new ArrayDeque<>(); public static void main(String[] args) { // Build the graph graph.put("A", Arrays.asList("B", "C")); graph.put("B", Arrays.asList("D", "E")); graph.put("C", Arrays.asList("F")); graph.put("D", Arrays.asList()); graph.put("E", Arrays.asList()); graph.put("F", Arrays.asList()); String start = "A"; String target = "F"; dfs(start, target); } private static void dfs(String node, String target) { if (node.equals(target)) { System.out.println("Target found: " + node); return; } stack.push(node); visited.add(node); for (String neighbor : graph.getOrDefault(node, new ArrayList<>())) { if (!visited.contains(neighbor)) { dfs(neighbor, target); } } stack.pop(); } }