天天看点

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())));