定义一个 Collection 类型的 集合,存储 字符串。
请定义一个 Collection 类型的集合,存储以下字符串:
完成以下功能:
public class Test {
public static void main(String[] args) {
System.out.println("嗨客网(www.haicoder.net)\n");
Collection<String> coll = new ArrayList<>();
coll.add("JavaEE企业级开发");
coll.add("Oracle高级编程");
coll.add("MySQL从入门到精通");
coll.add("Java架构师之路");
Iterator<String> it = coll.iterator();
// 使用迭代器遍历所有元素,并打印
System.out.println("\n=========使用迭代器遍历所有元素==========");
while(it.hasNext()){
System.out.println(it.next());
}
// 使用迭代器遍历所有元素,筛选书名小于10个字符的,并打印
System.out.println("\n=========遍历所有元素,打印小于10个字符的字符串==========");
it = coll.iterator();
while(it.hasNext()){
String str = it.next();
if(str.length()< 10){
System.out.println(str);
}
}
// 使用迭代器遍历所有元素,打印包含“Java”的字符串
System.out.println("\n=========遍历所有元素,打印包含“Java”的字符串==========");
it = coll.iterator();
while(it.hasNext()){
String str = it.next();
if(str.contains("Java")){
System.out.println(str);
}
}
// 删除包含“Oracle”的字符串,打印集合
System.out.println("\n=========删除包含“Oracle”的字符串,打印集合==========");
it = coll.iterator();
while(it.hasNext()){
String str = it.next();
if(str.contains("Oracle")){
it.remove();
}
}
it = coll.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
}
运行结果如下图:
以上案例实现集合遍历,并按要求打印字符串。