一、JAVA集合类
为了保存数量不确定的数据,以及保存具有映射关系的数据(关联数组),java提供了集合类。所有集合类位于java.util包下。
集合类就像容是器,现实生活中容器的功能,无非就是添加对象、删除对象、清空容器、判断容器是否为空等,集合类就为这些功能提供对应的方法。
java集合类是由两个接口Collection 和 Map派生而出
Collection |
Map |
||
Set |
Queue |
List |
EnumMap IdentityHashMap HashMap LinkedHashMap Hashtable Properties SortedMap TreeMap WeakHashMap |
EnumSet SortedSet HashSet TreeSet LinkedHashSet |
Deque PriorityQueue ArrayDeque
|
LinkedList ArrayList Vector Stack |
Map实现类用于保存具有映射关系的数据。
Set 无法记住添加元素的顺序,所有元素不能重复且无序
List 像一个长度可变的数组
二、Collection和Iterator接口
Iterator类与Collection、Map不同,主要用于遍历Collection中的元素,其对象也被称为迭代器
1、Collection使用如下:
Collection实现类都重写了toString()方法,使用System.out.println()输出集合对象时,将输出[ele1,ele2…….]的形式。
2、遍历Collection
遍历过程中不要使用集合的remove对集合进行删除操作,会抛出异常
Iterator迭代器的使用
程序示范4种迭代方式:
public static void main(String[] args) {
………………………
//获取books集合对应的迭代器
Iterator it = books.iterator();
//1.使用Lambda表达式遍历集合
books.forEach(obj->System.out.println(“迭代集合元素:”+obj));
//2.使用Iterator遍历集合
while(it.hasNext()) { //迭代是否结束
//返回Object类型的数据,需要强制转换
String book = (String)it.next();
System.out.println(book);
if(book.equals("迭代器")) {
//从集合中删除book对应的元素
it.remove();
}
......
}
……….
//3.使用Lambda表达式遍历Iterator
it.forEachRemaining(obj->System.out.println(“迭代集合元素:”+obj));
//4.使用foreach循环遍历集合元素
for(Object obj : books){
String book = (String)obj;
……….
}
}
3、Predicate操作集合
//批量删除符合条件的元素(过滤集合),删除所有长度小于10 的字符串元素
Book.removeIf(ele -> ((String)ele).length()<10);
例如:Predicate的test方法可以判断该对象是否满足Predicate指定的条件,对于统计集合中符合某个条件的元素有多少,只需要构造一个方法:
public static void main(String[] args) {
//统计包含“Predicate”的元素
System.out.println(calAll(books,ele -> ((String)ele).contains("Predicate")));
//统计包含“test”的元素
System.out.println(calAll(books,ele -> ((String)ele).contains("test")));
//统计字符串大于10的元素
System.out.println(calAll(books,ele -> ((String)ele).length()>10));
}
public static int calAll(Collection books,Predicate p) {
int count = 0;
for(Object obj : books) {
if(p.test(obj)) { //满足Predicate则++
count++;
}
}
return count;
}
原文:https://www.cnblogs.com/JIATCODE/p/12287205.html