有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在ArrayList中搜索相似性

我有一个字符串的arrayList,我想在微调器或下拉菜单中显示,但大多数情况下,我会让字符串重复,我要做的是在arrayList中搜索相似性,如果它发现一个字符串,例如“Hello World”在arrayList中出现7次,删除其他6并将7分配给它以显示它发生了7次,因此我的新字符串将是“Hello world(7)”,有人可以帮助我如何在下面的代码中实现这一点:

for(int i = 0; i < timesCalleddb.getAllTimesCalled(missedCall.getNumber()).size(); i++)
    {

        if(timesCalleddb.getAllTimesCalled(missedCall.getNumber()).get(i) ==
                timesCalleddb.getAllTimesCalled(missedCall.getNumber()).get(i+1))
        {
           //where am guessing the implementation my problem should be
        }

    }

共 (4) 个答案

  1. # 1 楼答案

    要从List中删除重复的String,请使用以下命令:

    List<String> arrayList = new ArrayList<>();
    // Your elements must be added to the arrayList, before progressing to the next step.
    Set<String> set = new HashSet<>();
    set.addAll(arrayList );
    
    // Code for getting count of each String
    int count = 0;
    List<Integer> arrayListCount = new ArrayList<>();
    for (Iterator<String> it = set.iterator(); it.hasNext(); ) {
        String str = it.next();
        arrayListCount.add(count , 0);
        for(int i = 0; i < arrayList.size(); i++){
            String s = arrayList.get(i);
            if (str.equals(s)) {
                arrayListCount.set(count , arrayListCount.get(count) + 1);
           }                
        }
        count++;
    }
    // Code for getting count ends here
    
    arrayList.clear();
    arrayList.addAll(set);
    

    注意:不会保留List的序列

    希望有帮助

  2. # 2 楼答案

    您应该考虑使用MAP数据结构,因为您必须存储计数器,否则,哈希集将是完美的:

    ArrayList<String> strs = ...;
    
    HashMap<String, Integer> counter = new HashMap<String, Integer>();
    
    for(String s : strs) {
        counter.put(s, counter.get(s) == null ? 1 : counter.get(s) + 1);
    }
    
    for(String s : counter.keySet()) {
        System.out.println(s + " (" + counter.get(s) + ")");
    }
    
  3. # 3 楼答案

    您可以使用此代码根据列表的特定字符串筛选CustomList。如果要计算发生次数,可以在循环中添加一些计数器

    List<MyCustomObject> arrayList = new ArrayList<>();
    List<MyCustomObject> result = new ArrayList<>();
    
    Set<String> set = new HashSet<>();
    for(MyCustomObject item : arrayList) {
       if(set.add(item.getSomeString()) {
           resultArray.add(item);
       }
    }
    arrayList.clear();
    arrayList.addAll(result);
    
  4. # 4 楼答案

    您可以执行以下操作:

    1. List上迭代,并生成一个HashMap<String, Integer>,指示每个String出现的次数
    2. 使用list = new ArrayList<String>(new LinkedHashSet<String>(list));List中删除重复项。使用LinkedHashSet表示保持顺序
    3. 通过在List上迭代并根据map.get(string)1还是大于1添加stringstring + " (" + map.get(string) + ")"来建立一个新的List