我有两个数组列表我想将请求的元素与允许的元素进行比较。
如果请求的元素出现在允许的元素中,则应该打印
"Allowed elements <element1>, <element2>, <element3>"
和
如果请求的元素不在允许的元素中,则应该打印
"Not allowed <element1>, <element2>, <element3>"
我的代码
public class testList {
public static void main(String[] args) {
ArrayList<String> Alist = new ArrayList<String>();
ArrayList<String> Blist = new ArrayList<String>();
// allowed elements
Alist.add("NAME");
Alist.add("SUBJECT");
Alist.add("MARKS");
// requested elements
Blist.add("NAME");
Blist.add("AGE");
Blist.add("DOB");
Blist.add("SUBJECT");
Blist.add("MARKS");
Blist.add("AVERAGE");
Blist.add("MOBILE");
Blist.add("EMAIL");
}
}
,结果应为:
如果要求EMAIL和MOBILE不在允许的元素中,则应打印&#34; 不允许EMAIL和MOBILE &#34;
如果要求NAME,SUBJECT和MARKS允许的元素应该打印&#34; 允许NAME,SUBJECT和MARKS &#34;
答案 0 :(得分:1)
这是一个非常简单的问题代码,试试这个并告诉我是否有:
StringBuilder allowBuilder = new StringBuilder("Allowed ");
StringBuilder notAllowBuilder = new StringBuilder("Not allowed ");
List<String> allowList = new ArrayList<String>();
List<String> notAllowList = new ArrayList<String>();
for (String blistItem : Blist) {
if (Alist.contains(blistItem)) {
allowList.add(blistItem);
} else {
notAllowList.add(blistItem);
}
}
for (int i = 0; i < allowList.size(); i++) {
if (i == 0) {
allowBuilder.append(allowList.get(i));
} else {
if (i + 1 < allowList.size()) {
allowBuilder.append(", ").append(allowList.get(i));
} else {
allowBuilder.append(" and ").append(allowList.get(i));
}
}
}
for (int i = 0; i < notAllowList.size(); i++) {
if (i == 0) {
notAllowBuilder.append(notAllowList.get(i));
} else {
if (i + 1 < notAllowList.size()) {
notAllowBuilder.append(", ").append(notAllowList.get(i));
} else {
notAllowBuilder.append(" and ").append(notAllowList.get(i));
}
}
}
System.out.println(notAllowBuilder.toString());
System.out.println(allowBuilder.toString());
<强>输出:强>
Not allowed AGE, DOB, AVERAGE, MOBILE and EMAIL
Allowed NAME, SUBJECT and MARKS
答案 1 :(得分:0)
试试这个:
List<String> newBlist = new ArrayList<String>(Blist);
newBlist.removeAll(Alist);
StringBuilder response = new StringBuilder();
List<String> responseList;
if (newBlist.isEmpty()) {
response.append("Allowed ");
responseList = Blist;
} else {
response.append("Not Allowed ");
responseList = newBlist;
}
for (String str : responseList) {
response.append(str).append(" ");
}
System.out.println(response.toString());