天天看點

Java集合常用方法

1、Java集合常用方法

1.1、List,Map初始化

ArrayList<String> list = new ArrayList<String>(){{
    add("test1");
    add("test2");
}};

HashMap<String, String> map = new HashMap<String, String>() {
    {
        map.put("name", "test");  
        map.put("age", "20"); 
    }
};

// 不可修改的map
private final Map<String,String> map = Collections.unmodifiableMap(map);
           

雙括号”{{}}”,用來初始化,使代碼簡潔易讀,但是性能稍差13%。

第一層括弧實際是定義了一個匿名内部類 (Anonymous Inner Class)。

第二層括弧實際上是一個執行個體初始化塊 (instance initializer block),這個塊在内部匿名類構造時被執行。

然後這邊還有一點需要明白,執行個體初始化塊的代碼在編譯器編譯過後,是放在類的構造函數裡面的,并且是在原構造函數代碼的前面。

1.2、List轉為String字元串并以符号分隔

String names= Joiner.on(" ").join(list);
String str = list.stream().map(String::valueOf).collect(Collectors.joining(","));
           

1.3、String切割成Array

String[] ary = str.splic('字元');
           

1.4、Array轉成List

List<String> list = Array.asList(數組);
           

1.5、List轉成Array

String[] ary = list.toArray();
           

2、stream()的一些集合轉換

2.1、List<entity>泛型擷取實體的某一字段

示例
List<String> titles = titleList
.stream()
.map(e -> e.get(ConstantUtil.TITLE))
.collect(Collectors.toList());
優化:
List<String> fieldList = mountTableVoList
.stream()
.map(ResMountTable::getFieldName)
.collect(Collectors.toList());
           

2.2、List<A>轉換成List<B>

listA.stream().map(this::方法入參A傳回B). collect(Collectors.toList());
           

2.3、取List<entity>中存在有一項的字段是啥

boolean result = listA.stream().filter(item->item.x1==1).findFirst(). isPresent();
           

2.4、求和

Integer result = list.stream().collect(Collectors.summingInt(Student::getAge));
System.out.println("所有學生年齡之和 : " + reuslt);

BigDecimal result2 = userList.stream()
            // 将user對象的age取出來map為Bigdecimal
            .map(User::getAge)
            // 使用reduce()聚合函數,實作累加器
            .reduce(BigDecimal.ZERO,BigDecimal::add);
           

2.5、做Stream()操作

Stream.of();
           

3、Collections,CollectionUtils

import java.utils;
import org.apache.commons.collections.CollectionUtils;
           

3.1、集合空判斷

CollectionUtils.isEmpty(list);
           

3.2、排序

list.sort(Collections.reverseOrder());
Arrays.sort(ary, Collections.reverseOrder());
           

4、其他第三方庫

4.1、com.google.common.collection

#構造map
ImmutableMap.of();
           

5、一些demo

5.1、一個排序demo

import java.io.*;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Vector;

class Box{
    public float score;
}

class BoxComparator implements Comparator<Box> {
    public int compare(Box a, Box b) {
        if(a.score < b.score){
            return 1;
        }else if(a.score == b.score){
            return 0;
        }else{
            return -1;
        }
    }
}

class test {
    public static void main (String[] args) throws java.lang.Exception {
        Vector<Box> boxes = new Vector<Box>();
        Box b1 = new Box();
        b1.score = 0.1f;
        
        Box b2 = new Box();
        b2.score = 0.2f;
        
        Box b3 = new Box();
        b3.score = 0.3f;
        
        Box b4 = new Box();
        b4.score = 0.4f;
        
        boxes.add(b1);
        boxes.add(b2);
        boxes.add(b3);
        boxes.add(b4);
        
        Comparator<Box> cmp =new BoxComparator();
        Collections.sort(boxes, cmp);
        
        for(int i=0; i<boxes.size();i++){
            Box box = boxes.get(i);
            System.out.printf("%f\n",box.score);
        }
    }
}
           

5.2、一個分組demo

5.2.1、group by

業務場景:有時候我們需要在資料庫中group by 查詢資料,如果這時候又涉及到多張表(大于3張)時,group by的字段又沒有索引,這時候sql執行效率就會比較差,優化的一個方法就是把資料全查出來,然後在記憶體中group by,也即是對List操作group by。

public class listUtil {
    /**
   * 分組依據接口,用于集合分組時,擷取分組
   * T為要groupBy屬性是類型,這個傳回值為要groupBy的屬性值
   */
   public interface GroupBy<T> {
       T groupBy(Object obj) ;
   }
   
   /**
   * 通過屬性對集合分組
   * @param colls
   * @param gb
   * @return
   * extends Comparable<T> 
   */
   public static final <T,D> Map<T ,List<D>> 
   groupBy(Collection<D> colls ,GroupBy<T> gb){
       Map<T ,List<D>> map = new HashMap<T, List<D>>();
       
       Iterator<D> iter = colls.iterator() ;
       
       while(iter.hasNext()) {
           D d = iter.next() ;
           T t = gb.groupBy(d) ;
           if(map.containsKey(t)) {
               map.get(t).add(d) ;
           } else {
               List<D> list = new ArrayList<D>() ;
               list.add(d) ;
               map.put(t, list) ;
           }
       }
       return map ;
   }
   
    /**
    * 通過屬性名稱對集合分組
    * @param colls
    * @param fieldName為集合中對象的屬性名稱
    * @return
    * extends Comparable<T> 
    */
   public static final <T,D> Map<T ,List<D>> 
   groupBy(Collection<D> colls ,String fieldName){
       return groupBy(colls,new GroupBy<T>(){
           @Override
           public T groupBy(Object obj){
               Object v=getFieldValueByName(obj,fieldName);
               return (T)v;
           }
       });
   }
   
  /** 
  * 根據屬性名稱擷取屬性值 
  * */  
  public static Object getFieldValueByName(Object o,String fieldName) {  
      try {    
          String firstLetter = fieldName.substring(0, 1).toUpperCase();    
          String getter = "get" + firstLetter + fieldName.substring(1);    
          Method method = o.getClass().getMethod(getter, new Class[] {});    
          Object value = method.invoke(o, new Object[] {});    
          return value;    
      } catch (Exception e) {    
          logger.error(e.getMessage(),e);    
          return null;    
      }    
  }
}
           

5.2.2、使用java8 stream groupingBy 方式處理

List<Employee>  employeeList = new ArrayList<>();
Employee employee1 = new Employee("Alice","London",200);
Employee employee2 = new Employee("Bob","London",150);
Employee employee3 = new Employee("Charles","New York",160);
Employee employee5 = new Employee("Charles","",300);
Employee employee4 = new Employee("Dorothy","Hong Kong",190);
employeeList.add(employee1);
employeeList.add(employee2);
employeeList.add(employee3);
employeeList.add(employee4);
employeeList.add(employee5);
	
//groupBy
Map<String, List<Employee>> employeesByCity = employeeList
       .stream().collect(groupingBy(Employee::getCity));
System.out.println(employeesByCity);
//groupby count
System.out.println(employeeList
	 .stream()
	 .collect(groupingBy(Employee::getCity,counting())));