2016-05-27 34 views
-2

我有數組列表的自定義對象類型,我想搜索的字符串是存在於對象的值,那我怎麼才能找到它指出,反對那些 有搜索字符串如何在自定義對象類型數組列表中搜索?什麼是最好和最快的方式

+2

請創建MCVE向我們展示你嘗試過什麼http://stackoverflow.com/help/mcve的 –

+0

可能的複製【JAVA:查找數組列表字符串(http://stackoverflow.com/questions/32304214/java-find-string-in-array-list) – brianlmerritt

+0

這些答案不是我的解決方案我想用最快的方式在數組列表中使用HashSet進行搜索 –

回答

0

你可以嘗試一些像這樣:

package com.company; 

import java.util.ArrayList; 
import java.util.List; 

public class Test { 
    private String val; 

    public Test(String s) { 
     this.val = s; 
    } 

    public static void main(String[] args) { 
     List<Test> values = new ArrayList<>(); 
     values.add(new Test("one")); 
     values.add(new Test("two")); 
     values.add(new Test("three")); 

     System.out.println(listContains(values, "two")); 
     System.out.println(listContains(values, "five")); 
    } 

    public static boolean listContains(List<Test> customTypeList, String searchedString) { 
     return customTypeList.stream().anyMatch((v) -> v.val.contains(searchedString)); 
    } 
} 

如果你在你的列表(子不感興趣)尋找最快的解決方案並搜查字符串正是從對象的值,那麼你可能想從你的對象的字符串映射到這些對象的這樣的參考資料:

 (...) 
     List<Test> values = new ArrayList<>(); 
     values.add(new Test("one")); 
     values.add(new Test("two")); 
     values.add(new Test("three")); 

     Map<String, Test> indices = new HashMap<>(); 
     for (Test v : values) { 
      indices.put(v.val, v); 
     } 

     System.out.println(indices.containsKey("two")); 
     System.out.println(indices.containsKey("five")); 
     // or... 
     System.out.println(indices.keySet().contains("two")); 
     System.out.println(indices.keySet().contains("five")); 
     (...) 

重要提示:只要您更改列表的內容,就需要更新索引。請注意,在這種情況下,對象內部的字符串值必須是這些對象的有效鍵(唯一值)。例如:

public static void main(String[] args) { 
     List<Test> values = new ArrayList<>(); 
     Map<String, Test> indices = new HashMap<>(); 

     addToList(values, indices, new Test("one")); 
     addToList(values, indices, new Test("two")); 
     addToList(values, indices, new Test("three")); 

     System.out.println(indices.keySet().contains("two")); 
     System.out.println(indices.keySet().contains("five")); 

     removeFromList(values, indices, "two"); 

     System.out.println(indices.keySet().contains("two")); 
    } 

    private static void addToList(List<Test> values, Map<String, Test> indices, Test item) { 
     values.add(item); 
     indices.put(item.val, item); 
    } 

    private static void removeFromList(List<Test> values, Map<String, Test> indices, String key) { 
     Test item = indices.remove(key); 
     values.remove(item); 
    } 
+0

沒有將方法命名爲stream()數組列表 –

+2

In Java 8有: java.util.Collection => public java.util.stream.Stream stream()[請參閱:https://docs.oracle.com/javase/8/docs/api/java/util /stream/package-summary.html] – alwi

+0

我有Java(TM)SE運行環境(build 1.8.0_92-b14),它不給Array列表上的任何方法流 –

相關問題