一、引入Maven依賴
<dependency> <groupId>commons-collections</groupId> <artifactId>commons-collections</artifactId> <version>3.2.2</version> </dependency>
二、常用API說明
以下使用到一些BO
Person.java
public class Person { private String username; private int age; private float stature;//身高 private boolean sex;//性別 private List list = new ArrayList(); private String[] friendsNames; private Map<String, String> maps = new HashMap<String, String>(); private Address address; public Person() { } public Person(String username) { this.username = username; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public float getStature() { return stature; } public void setStature(float stature) { this.stature = stature; } public boolean isSex() { return sex; } public void setSex(boolean sex) { this.sex = sex; } @SuppressWarnings("unchecked") public List getList() { return list; } @SuppressWarnings("unchecked") public void setList(List list) { this.list = list; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } public Map<String, String> getMaps() { return maps; } public void setMaps(Map<String, String> maps) { this.maps = maps; } public String[] getFriendsNames() { return friendsNames; } public void setFriendsNames(String[] friendsNames) { this.friendsNames = friendsNames; } @Override public String toString() { return "Person{" + "username='" + username + '\'' + ", age=" + age + ", address=" + address + '}'; } }
Address.java
public class Address { private String email; private List<String> telephone; public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public List<String> getTelephone() { return telephone; } public void setTelephone(List<String> telephone) { this.telephone = telephone; } @Override public String toString() { return "Address{" + "email='" + email + '\'' + ", telephone=" + telephone + '}'; } }
常用API如下:
import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Properties; import java.util.Set; import org.apache.commons.beanutils.BeanComparator; import org.apache.commons.collections.BufferUtils; import org.apache.commons.collections.Closure; import org.apache.commons.collections.ComparatorUtils; import org.apache.commons.collections.EnumerationUtils; import org.apache.commons.collections.FastArrayList; import org.apache.commons.collections.IteratorUtils; import org.apache.commons.collections.KeyValue; import org.apache.commons.collections.ListUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.collections.Predicate; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.PredicateUtils; import org.apache.commons.collections.SetUtils; import org.apache.commons.collections.Transformer; import org.apache.commons.collections.TransformerUtils; import org.apache.commons.collections.comparators.ComparableComparator; import org.apache.commons.collections.comparators.ComparatorChain; import org.apache.commons.collections.functors.EqualPredicate; import org.apache.commons.collections.functors.NotNullPredicate; import org.apache.commons.collections.functors.TruePredicate; import org.apache.commons.collections.functors.UniquePredicate; import org.apache.commons.collections.keyvalue.DefaultKeyValue; import org.apache.commons.collections.list.PredicatedList; /** * Collections java集合框架操作. * 常用類 * ① CollectionUtils 集合操作類 * ② PredicateUtils 斷言Predicate工具類 * ③ ListUtils List操作工具類 * ④ MapUtils Map操作工具類 * ⑤ SetUtils Set集合操作 * ⑥ IteratorUtils Iterator操作工具類型 * ⑦ ComparatorUtils * ⑧ BufferUtils * * 其他 * TransformerUtils * FastTreeMap * FastHashMap * FastArrayList */ public class CollectionsDemo { private static List<String> list1 = new ArrayList<>(Arrays.asList(new String[]{"1", "2", "3", "1", "5"})); private static List<String> list2 = new ArrayList<>(Arrays.asList(new String[]{"2", "3", "1", "4"})); private static List<String> list3 = new ArrayList<>(Arrays.asList(new String[]{"1", "2"})); private static void testIteratorUtils() { List<String> list = IteratorUtils.toList(list1.iterator()); System.out.println("根據集合迭代器反向獲得集合" + list); /* * ListIterator是一個功能更加強大的, 它繼承於Iterator接口,只能用於各種List類型的訪問。 * 雙向移動(向前/向后遍歷) * 產生相對於迭代器在列表中指向的當前位置的前一個和后一個元素的索引. * 可以使用set()方法替換它訪問過的最后一個元素. */ ListIterator listIterator = IteratorUtils.toListIterator(list.iterator()); System.out.println(listIterator.next()); // 獲取集合迭代器 Iterator iterator = IteratorUtils.getIterator(list1); } /** * @MethodName testPredicate * @Description Predicate相關的一些操作(PredicateUtils) */ private static void testPredicate() { Predicate helloPre = EqualPredicate.getInstance("hello"); System.out.println("EqualPredicate判斷是否相等:" + helloPre.evaluate("hello")); Predicate notNullPredicate = NotNullPredicate.getInstance(); System.out.println("NotNullPredicate判斷是否為空, 空字符串返回的是true:" + notNullPredicate.evaluate(null)); Predicate predicate = UniquePredicate.getInstance(); // 相當於一開始就對集合做了限制(唯一),后續的操作如果越過了限制就會拋異常 List<String> list = PredicatedList.decorate(new ArrayList<>(), predicate); list.add("zs"); //list.add("zs"); // 拋出異常 Cannot add Object 'zs' - Predicate 不能重復 System.out.println(list.size()); } /** * @MethodName testSetUtils * @Description SetUtils相關測試 */ private static void testSetUtils() { Set<String> strSet = new HashSet(list1); // 轉線程安全 Set<String> synchronizedSet = SetUtils.synchronizedSet(strSet); Set<String> orderSet = SetUtils.orderedSet(strSet); orderSet.add("67"); System.out.println("轉有序的Set,類似List是有順序的:" + orderSet); Predicate predicate = new Predicate() { @Override public boolean evaluate(Object object) { String str = (String) object; return Integer.parseInt(str) > 0; } }; Set predicatedSet = SetUtils.predicatedSet(strSet, new Predicate() { @Override public boolean evaluate(Object object) { // 這里只能返回true, 返回false會報錯, 即斷言都大於0才行 return Integer.parseInt(object.toString()) > 0; } }); System.out.println("predicatedSet篩選:" + predicatedSet); } /** * @MethodName testMapUtils * @Description MapUtils相關測試 */ private static void testMapUtils() { Map<String, String> emptyMap = new HashMap(); Map<String, String> map = new HashMap(); map.put("宋江", "及時雨"); map.put("武松", "行者"); map.put("林沖", "豹子頭"); map.put("李逵", "黑旋風"); map.put("吳用", "智多星"); System.out.println("MapUtils.isNotEmpty判斷Map不為空:" + MapUtils.isNotEmpty(emptyMap)); DefaultKeyValue keyValue = new DefaultKeyValue(); keyValue.setKey("蕭讓"); keyValue.setValue("聖手書生"); MapUtils.putAll(map, new DefaultKeyValue[]{keyValue}); System.out.println("MapUtils.putAll:" + MapUtils.getString(map, "蕭讓")); // MapUtils有很多getXXX()和getXXXValue()方法,這里就不贅述 // 轉成線程安全的Map MapUtils.synchronizedMap(map); // 將Map轉Properties Properties properties = MapUtils.toProperties(map); // 這個有什么用呢? MapUtils.multiValueMap(map, List.class); } /** * @MethodName testListUtils * @Description ListUtils相關測試 */ private static void testListUtils() { System.out.println("判斷兩個集合是否相等(采用元素equal):" + ListUtils.isEqualList(list1, list2)); //取交集 List<String> intersectionList = (List<String>) ListUtils.intersection(list1, list2); System.out.println("兩個集合的交集intersection:" + String.join(",", intersectionList)); // 交集, list1 與 list2 存在相同元素,list1集合只保留list2中存在的元素 List<String> retainAllList = (List<String>) ListUtils.retainAll(list2, list1); System.out.println("兩個集合的交集retainAll:" + String.join(",", retainAllList)); // 並集, 不去重 List<String> unionList = (List<String>) ListUtils.union(list1, list2); System.out.println("兩個集合的並集union:" + String.join(",", unionList)); // list1 - list2 = 剩余元素組成的集合 List<String> subtractList = (List<String>) ListUtils.subtract(list1, list2); System.out.println("list1 - list2:" + String.join(",", subtractList)); // 轉換為線程安全的List ListUtils.synchronizedList(list1); // 這個不知道用來干什么,名義上是取重的列表合並,但是如果某個列表存在重復元素,合並后並不會剔除 System.out.println("sum:" + String.join(",", ListUtils.sum(list1, list2))); System.out.println("刪除列表:" + String.join(",", ListUtils.removeAll(list1, list2))); } /** * @MethodName testCollectionUtils * @Description CollectionUtils相關測試 */ private static void testCollectionUtils() { // 以下的在使用到Predicate時,使用了labmbda表達式 // 常用的predicate也可以通過PredicateUtils構造出來, 如: //返回為null的collection數據 // CollectionUtils.filter(list1, PredicateUtils.nullPredicate()); //取交集 List<String> intersectionList = (List<String>) CollectionUtils.intersection(list1, list2); System.out.println("兩個集合的交集:" + String.join(",", intersectionList)); // list1 與 list2 存在相同元素,list1集合只保留list2中存在的元素 List<String> retainAllList = (List<String>) CollectionUtils.retainAll(list2, list1); System.out.println("兩個集合的交集:" + String.join(",", retainAllList)); // 並集, 不去重 List<String> unionList = (List<String>) CollectionUtils.union(list1, list2); System.out.println("兩個集合的並集:" + String.join(",", unionList)); CollectionUtils.addAll(list1, list2.toArray()); System.out.println("將一個數組或集合中的元素全部添加到另一個集合中:" + list1); // 差集, 不去重 List<String> disjunctionList = (List<String>) CollectionUtils.disjunction(list1, list2); System.out.println("兩個集合的差集:" + String.join(",", disjunctionList)); // list1 - list2 = 剩余元素組成的集合 List<String> subtractList = (List<String>) CollectionUtils.subtract(list1, list2); System.out.println("list1 - list2:" + String.join(",", subtractList)); //統計集合中各元素出現的次數,並Map<Object, Integer>輸出 Map cardinalityMap = CollectionUtils.getCardinalityMap(list1); cardinalityMap.forEach((k, v) -> System.out.println(k + ":" + v)); // a是否b集合子集,a集合大小<=b集合大小 boolean subCollection = CollectionUtils.isSubCollection(list3, list2); System.out.println("a是否b集合子集,a集合大小<=b集合大小:" + subCollection); // a是否b集合子集,a集合大小<b集合大小 boolean properSubCollection = CollectionUtils.isProperSubCollection(list3, list2); System.out.println("a是否b集合子集,a集合大小<b集合大小:" + properSubCollection); // 兩個集合是否相同 boolean equalCollection = CollectionUtils.isEqualCollection(list3, list2); System.out.println("兩個集合是否相同:" + equalCollection); // 某元素在集合中出現的次數 int cardinality = CollectionUtils.cardinality("1", list1); System.out.println("某元素在集合中出現的次數:" + cardinality); // 返回集合中滿足函數式的唯一元素,只返回最先處理符合條件的唯一元素 Object value = CollectionUtils.find(list1, itm -> { return Integer.valueOf(itm.toString()) > 1; }); System.out.println("find:" + value); //返回符合條件的collection Collection resultSelect = CollectionUtils.select(list1, itm -> Integer.valueOf(itm.toString()) > 1); System.out.println("select:" + String.join(",", resultSelect)); //和select結果相反,返回不符合條件的collection Collection resultSelectReject = CollectionUtils.selectRejected(list1, itm -> Integer.valueOf(itm.toString()) > 1); System.out.println("selectRejected:" + String.join(",", resultSelectReject)); //判斷list1是否包含符合條件的元素 boolean resultExists = CollectionUtils.exists(list1, itm -> Integer.valueOf(itm.toString()) > 2); System.out.println("exists:" + resultExists); //返回list1符合條件的個數 int resultMatchNum = CollectionUtils.countMatches(list1, itm -> Integer.valueOf(itm.toString()) > 1); System.out.println("countMatches:" + resultMatchNum); //返回list1且只包含數據大於2 CollectionUtils.filter(list1, itm -> Integer.valueOf(itm.toString()) > 2); System.out.println("filter:" + String.join(",", list1)); //這個比較難理解,如果后面predicate都滿足,則返回list1, Collection resultCollect = CollectionUtils.predicatedCollection(list1, itm -> { //Returns a predicated (validating) collection backed by the given collection. return Integer.valueOf(itm.toString()) > 0; }); System.out.println("predicatedCollection:" + String.join(",", resultCollect)); //對集合中的對象中的某一屬性進行批量更新,closure為需要更新的屬性對象 List<Person> personList = new ArrayList(); Person person1 = new Person(); person1.setAge(25); personList.add(person1); Person person2 = new Person(); person2.setAge(17); personList.add(person2); CollectionUtils.forAllDo(personList, new Closure() { @Override public void execute(Object input) { Person pn = (Person) input; pn.setAge(pn.getAge() + 1); } }); System.out.println("forAllDo:" + personList.get(0).getAge()); // collect底層調用的transform方法, 將所有元素進行處理,並返回新的集合 List<Integer> collection = (List<Integer>) CollectionUtils.collect(list1, new Transformer() { @Override public Object transform(Object o) { int i = Integer.parseInt((String) o); return ++i; } }); System.out.println("collect:" + collection); System.out.println("判斷集合是否為空:" + CollectionUtils.isNotEmpty(list1)); System.out.println("判斷兩個集合是否有相同元素:" + CollectionUtils.containsAny(list1, list2)); System.out.println("返回集合中指定下標元素:" + CollectionUtils.get(list1, 2)); System.out.println("刪除相同元素后list1剩余元素:" + CollectionUtils.removeAll(list1, list2)); } public static void main(String[] args) { //CollectionsDemo.testCollectionUtils(); //CollectionsDemo.testListUtils(); //CollectionsDemo.testMapUtils(); //CollectionsDemo.testSetUtils(); //CollectionsDemo.testPredicate(); //CollectionsDemo.testIteratorUtils(); } }