简体   繁体   English

如何在对象的arrayList中进行迭代并通过前缀匹配获取结果集?

[英]How to iterate within arrayList of object and get the result set by prefix matching?

I have the following class: 我有以下课程:

class A {
    String s;
}

And the following list of lists of class A objects: 以下是class A对象列表的列表:

[{1s, 3f, 46h}, {333s, 67b, 1d, 67m, 67h}, {3a, 3x}, {34n, 22o, 34s},
 {40f, 22x, 4m}... and so on]

All I need is to iterate through this list, get the results and push into another output arrayList. 我需要的是遍历此列表,获取结果,然后推入另一个输出arrayList中。 Now what would be included in the result arrayList: 现在,结果arrayList中将包含什么:

1. Just skip those elements from the above input arrayList
   which have more than one String with same prefix(only the last character
   is the suffix here which will always be a single character alphabet; not digit).
   For example: from the above input arrayList the first element({1s, 3f, 46h}) 
   won't be skipped and will be pushed into the output arrayList
   as it doesn't have any String with the same prefix; as 1, 3 and 46 are different.
   But 2nd, 3rd and 4th elements will be skipped as they have matches
   (three prefixes with same 67 in 2nd element, two prefixes with same 3 in 3rd element
   and two prefixes with same 34 in 4th element).

   So, for the above input arrayList the output arrayList will be:
   [{1s, 3f, 46h}, {40f, 22x, 4m}]

Can anybody suggest me how can I do the above job in an easy and efficient way. 有人可以建议我如何以一种简单有效的方式完成上述工作。 Please give some sample code if possible. 如果可能,请提供一些示例代码。

Thanks! 谢谢!

Consider the following: 考虑以下:

I have tried out a logic, i will be happy, if this works for you. 我已经尝试了一种逻辑,如果这对您有用,我会很高兴。

`ArrayList<A> arrList` = [{1s, 3f, 46h}, {333s, 67b,67m, 67h}, {3a, 3x}, {40f, 22x, 4m}... and so on]


 ArrayList<String> newList = new ArrayList<String>();

for ( A a: arrList){

        for(String s : a) {

             int[] temp = a.indexOf(s);

             if (temp > 1){

                break; // will break the immediate loop, NOT the Outer loop

             }

            else{
                     newList.add(s);

              }

      }


}

So if I were writing tests for this, I would see that one of the things I need is to be able to determine the prefix. 因此,如果我正在为此编写测试,我会发现我需要做的一件事情就是能够确定前缀。 Given an A with string "55p", the prefix should be "55". 给定带字符串“ 55p”的A,前缀应为“ 55”。 Write a test for that. 为此编写一个测试。 Where does the prefix method belong? 前缀方法在哪里? Probably in the A class itself. 大概在A类本身。 It should look something like: 它看起来应该像这样:

public String prefix() {
    return ...;
}

Once you have that method, it's easy to iterate over all the A's in a list and determine if any of them have the same prefix. 一旦有了该方法,就可以轻松遍历列表中的所有A,并确定它们中的任何一个是否具有相同的前缀。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM