构造List
List<String> list = Arrays.asList("a", "b", "c");
List<String> list = new ArrayList(Arrays.asList("a", "b", "c"));
增
list.add("d"); [a, b, c] → [a, b, c, d]
list.add(1,"d"); [a, b, c] → [a, d, b, c]
list.addAll(list2); [a, b, c] [d, e, f] → [a, b, c, d, e, f]
list.addAll(1, list2); [a, b, c] [d, e, f] → [a, d, e, f, b, c]
删
list.remove(1); [a, b, a, c] → [a, a, c]
list.remove("a"); [a, b, a, c] → [b, a, c]
list.removeAll(list2);
改
list.set(1, "e") [a, b, c, d] → [a, 6, c, d]
list.replaceAll(a -> a + "@"); [a, b, c, d] → [a@, b@, c@, d@]
查
list.isEmpty()
list.size()
list.contains("a") 判断是否包含、包含返回true
list.get(0)
list.indexOf("a") 判断元素第一次出现的索引,不存在则返回-1
list.lastIndexOf("b") 获取元素最后一次出现的索引,不存在则返回-1
排序
list.sort(Comparator.comparing(a->a.length())); [aaaa, bbb, cc, d] → [d, cc, bbb, aaaa]
操作
list.retainAll(list2); 把你和我一样的都保留
list.removeAll(list2); 把你和我一样的都删除
list.addAll(list2); 把你的我都接纳进来
List<String> strings = list.subList(1, 3); [a, b, c, d] → [b, c]
String[] arr = list.toArray(new String[0]);
CollectionUtils
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.4</version>
</dependency>
CollectionUtils.isEmpty(list);
CollectionUtils.isNotEmpty(list)
CollectionUtils.retainAll(collA, collB);
CollectionUtils.union(collA, collB);
CollectionUtils.subtract(collA, collB);
CollectionUtils.disjunction(listA,listB);
CollectionUtils.unmodifiableCollection(Collection collection)
CollectionUtils.isEqualCollection(collA, collB);
参考
ArrayList最常用的方法总结
CollectionUtils有哪些666的方法