CollectionUtils工具类的常用方法[list排序,及list去重、map遍历]

集合判断:
  例1: 判断集合是否为空:

    CollectionUtils.isEmpty(null): true
  CollectionUtils.isEmpty(new ArrayList()): true  
  CollectionUtils.isEmpty({a,b}): false

例2: 判断集合是否不为空:

     	CollectionUtils.isNotEmpty(null): false
  CollectionUtils.isNotEmpty(new ArrayList()): false
  CollectionUtils.isNotEmpty({a,b}): true

CollectionUtils在真实项目中,是一个非常好用的工具类,使用非常频繁。它可以使代码更加简洁和安全。刚好在工作中利用这个工具类重构代码,顺便总结下分享分享:

并集
@Test
public void testUnion(){
String[] arrayA = new String[] { “A”, “B”, “C”, “D”, “E”, “F” };
String[] arrayB = new String[] { “B”, “D”, “F”, “G”, “H”, “K” };
List listA = Arrays.asList(arrayA);
List listB = Arrays.asList(arrayB);
//2个数组取并集
System.out.println(ArrayUtils.toString(CollectionUtils.union(listA, listB)));
//[A, B, C, D, E, F, G, H, K]
}
交集
@Test
public void testIntersection(){
String[] arrayA = new String[] { “A”, “B”, “C”, “D”, “E”, “F” };
String[] arrayB = new String[] { “B”, “D”, “F”, “G”, “H”, “K” };
List listA = Arrays.asList(arrayA);
List listB = Arrays.asList(arrayB);
//2个数组取交集
System.out.println(ArrayUtils.toString(CollectionUtils.intersection(listA, listB)));
//[B, D, F]

}
交集的补集(析取)
@Test
public void testDisjunction(){
String[] arrayA = new String[] { “A”, “B”, “C”, “D”, “E”, “F” };
String[] arrayB = new String[] { “B”, “D”, “F”, “G”, “H”, “K” };
List listA = Arrays.asList(arrayA);
List listB = Arrays.asList(arrayB);
//2个数组取交集 的补集
System.out.println(ArrayUtils.toString(CollectionUtils.disjunction(listA, listB)));
//[A, C, E, G, H, K]
}
差集(扣除)
@Test
public void testSubtract(){
String[] arrayA = new String[] { “A”, “B”, “C”, “D”, “E”, “F” };
String[] arrayB = new String[] { “B”, “D”, “F”, “G”, “H”, “K” };
List listA = Arrays.asList(arrayA);
List listB = Arrays.asList(arrayB);
//arrayA扣除arrayB
System.out.println(ArrayUtils.toString(CollectionUtils.subtract(listA, listB)));
//[A, C, E]

}
集合是否为空
@Test
public void testIsEmpty(){

class Person{}
class Girl extends Person{}

List first = new ArrayList<>();
List second = null;
List boy = new ArrayList<>();
//每个男孩心里都装着一个女孩
boy.add(new Girl());
//判断集合是否为空
System.out.println(CollectionUtils.isEmpty(first));   //true
System.out.println(CollectionUtils.isEmpty(second));   //true
System.out.println(CollectionUtils.isEmpty(boy));   //false

//判断集合是否不为空
System.out.println(CollectionUtils.isNotEmpty(first));   //false
System.out.println(CollectionUtils.isNotEmpty(second));   //false
System.out.println(CollectionUtils.isNotEmpty(boy));   //true

}
集合是否相等
@Test
public void testIsEqual(){

class Person{}
class Girl extends Person{
}

List first = new ArrayList<>();
List second = new ArrayList<>();
first.add(1);
first.add(2);
second.add(2);
second.add(1);
Girl goldGirl = new Girl();
List boy1 = new ArrayList<>();
//每个男孩心里都装着一个女孩
boy1.add(new Girl());
List boy2 = new ArrayList<>();
//每个男孩心里都装着一个女孩
boy2.add(new Girl());
//比较两集合值
System.out.println(CollectionUtils.isEqualCollection(first,second));   //true
System.out.println(CollectionUtils.isEqualCollection(first,boy1));   //false
System.out.println(CollectionUtils.isEqualCollection(boy1,boy2));   //false

List boy3 = new ArrayList<>();
//每个男孩心里都装着一个女孩
boy3.add(goldGirl);
List boy4 = new ArrayList<>();
boy4.add(goldGirl);
System.out.println(CollectionUtils.isEqualCollection(boy3,boy4));   //true

}
不可修改的集合
我们对c进行操作,s也同样获得了和c相同的内容,这样就可以避免其他人员修改这个s对象。有时候需要对它进行保护,避免返回结果被人修改。

@Test
public void testUnmodifiableCollection(){
Collection c = new ArrayList<>();
Collection s = CollectionUtils.unmodifiableCollection©;
c.add(“boy”);
c.add(“love”);
c.add(“girl”);
//! s.add(“have a error”);
System.out.println(s);
}
Collections.unmodifiableCollection可以得到一个集合的镜像,它的返回结果是不可直接被改变,否则会提示错误

java.lang.UnsupportedOperationException
at org.apache.commons.collections.collection.UnmodifiableCollection.add(UnmodifiableCollection.java:75)

Comparator 的使用有两种方式
Collections.sort(list,Comparator);
list.sort(Comparator);
其实主要是看 Comparator 接口的实现,重写里面的 compare 方法。代码如下:

//自定义排序1
        Collections.sort(list, new Comparator() {
@Override
public int compare(Student o1, Student o2) {
        return o1.getId() - o2.getId();
        }
        });

compare(Student o1, Student o2) 方法的返回值跟 Comparable<> 接口中的 compareTo(Student o) 方法 返回值意思相同。另一种写法如下:

  //自定义排序2
    list.sort(new Comparator() {
@Override
public int compare(Student o1, Student o2) {
        return o1.getId() - o2.getId();
        }
        });

List转String

public String listToString(List list, char separator) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            sb.append(list.get(i)).append(separator);
        }
        return sb.toString().substring(0, sb.toString().length() - 1);
    }

-------遍历arrays List-------

import java.util.*;
public class Test{
 public static void main(String[] args) {
     List list=new ArrayList();
     list.add("Hello");
     list.add("World");
     list.add("HAHAHAHA");
     //第一种遍历方法使用foreach遍历List
     for (String str : list) {            //也可以改写for(int i=0;i ite=list.iterator();
     while(ite.hasNext())//判断下一个元素之后有值
     {
         System.out.println(ite.next());
     }
 }
}

解析
三种方法都是用来遍历ArrayList集合,第三种方法是采用迭代器的方法,该方法可以不用担心在遍历的过程中会超出集合的长度。
-------遍历Map-------

import java.util.*;
 
public class Test{
     public static void main(String[] args) {
      Map map = new HashMap();
      map.put("1", "value1");
      map.put("2", "value2");
      map.put("3", "value3");
      
      //第一种:普遍使用,二次取值
      System.out.println("通过Map.keySet遍历key和value:");
      for (String key : map.keySet()) {
       System.out.println("key= "+ key + " and value= " + map.get(key));
      }
      
      //第二种
      System.out.println("通过Map.entrySet使用iterator遍历key和value:");
      Iterator> it = map.entrySet().iterator();
      while (it.hasNext()) {
       Map.Entry entry = it.next();
       System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
      }
      
      //第三种:推荐,尤其是容量大时
      System.out.println("通过Map.entrySet遍历key和value");
      for (Map.Entry entry : map.entrySet()) {
       System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
      }
    
      //第四种
      System.out.println("通过Map.values()遍历所有的value,但不能遍历key");
      for (String v : map.values()) {
       System.out.println("value= " + v);
      }
     }
}


   //string 转为map转为list
                Gson gson = new Gson();
                Map map = new HashMap();
                map = gson.fromJson(propertyLabelVO.getLabelReason(), map.getClass());
                List workflowPropertyLabelResonListVOList = new ArrayList<>();
                WorkflowPropertyLabelResonListVO workflowPropertyLabelResonListVO = null;
                for (Map.Entry entry : map.entrySet()) {
                    workflowPropertyLabelResonListVO = new WorkflowPropertyLabelResonListVO();
                    workflowPropertyLabelResonListVO.setIsreach(entry.getValue());
                    workflowPropertyLabelResonListVO.setTitle(entry.getKey());
                    workflowPropertyLabelResonListVOList.add(workflowPropertyLabelResonListVO);
                }


-------去重操作-------

            Set set = new HashSet();
            List listNew = new ArrayList<>();
            set.addAll(list);
            listNew.addAll(set);
            list = listNew;

你可能感兴趣的:(java,List)