Java 如何在对象的arrayList中进行迭代,并通过前缀匹配得到结果集?
我有以下课程:Java 如何在对象的arrayList中进行迭代,并通过前缀匹配得到结果集?,java,string,collections,arraylist,iteration,Java,String,Collections,Arraylist,Iteration,我有以下课程: class A { String s; } 以及以下A类对象列表: [{1s, 3f, 46h}, {333s, 67b, 1d, 67m, 67h}, {3a, 3x}, {34n, 22o, 34s}, {40f, 22x, 4m}... and so on] 我所需要做的就是遍历这个列表,得到结果并推送到另一个输出arrayList。现在,结果arrayList中将包含哪些内容: 1. Just skip those elements from the abo
class A {
String s;
}
以及以下A类对象列表:
[{1s, 3f, 46h}, {333s, 67b, 1d, 67m, 67h}, {3a, 3x}, {34n, 22o, 34s},
{40f, 22x, 4m}... and so on]
我所需要做的就是遍历这个列表,得到结果并推送到另一个输出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}]
有人能告诉我怎样才能轻松有效地完成上述工作吗。请给
如果可能的话,提供一些示例代码
谢谢 考虑以下几点:
我已经尝试了一个逻辑,如果这对你有效,我会很高兴的
`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);
}
}
}
`arraylistarrlist`=[{1s,3f,46h},{333s,67b,67m,67h},{3a,3x},{40f,22x,4m}……等等]
ArrayList newList=新的ArrayList();
对于(A:arrList){
for(字符串s:a){
int[]温度=a.indexOf(s);
如果(温度>1){
break;//将中断立即循环,而不是外部循环
}
否则{
新列表。添加(s);
}
}
}
因此,如果我正在为此编写测试,我会发现我需要的事情之一是能够确定前缀。给定带有字符串“55p”的A,前缀应为“55”。为此编写一个测试。前缀方法属于哪里?可能是在A类本身。它应该看起来像:
public String prefix() {
return ...;
}
一旦有了这个方法,就可以很容易地迭代列表中的所有A,并确定它们是否有相同的前缀。这是家庭作业,不是吗?到目前为止你做了什么?@VivinPaliath和兰博编码员:还没开始。但我正在考虑这样做:遍历内部列表的所有元素,并像这样检查-假设第一个字符串是99x;然后,“99x”.substring(0,“99x”.length()-1)将给我前缀,然后我将把这个前缀推到另一个列表中。在得到一个列表中的所有前缀后,我考虑在这个新列表上使用一个自定义比较器来检查它是否多次具有相同的项,如果是,则从主输入arrayList中跳过该元素。有点笨拙!是吗?谢谢你的回复。我很欣赏你的想法,终于完成了任务。