List分组

分组实现
package test;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class GroupByList<V, T> {

  /**
   * 按照指定字段对list内数据进行分组
   * 
   * @param list
   * @param sortName
   * @return
   * @throws SecurityException
   * @throws NoSuchMethodException
   * @throws InvocationTargetException
   * @throws IllegalArgumentException
   * @throws IllegalAccessException
   */
  public Map<V, List<T>> groupBy(List<T> list, final String groupName)
      throws NoSuchMethodException, SecurityException, IllegalAccessException,
      IllegalArgumentException, InvocationTargetException {
    String method = "get" + groupName.substring(0, 1).toUpperCase() + groupName.substring(1);
    Map<V, List<T>> map = new HashMap<V, List<T>>();
    for (T t : list) {
      Method m1 = t.getClass().getMethod(method, null);
      V groupValue = (V) m1.invoke(t, null);
      if (map.containsKey(groupValue)) {
        List<T> tList = map.get(groupValue);
        tList.add(t);
      }
      else {
        List<T> tList = new ArrayList<T>();
        tList.add(t);
        map.put(groupValue, tList);
      }
    }
    return map;
  }
}
测试代码
package test;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.axis2.databinding.types.soapencoding.Array;

public class GroupByTest {

  public static void main(String[] args) throws NoSuchMethodException, SecurityException,
      IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    Employee staff11 = new Employee(21, "1group", 1990, 12, 25, 1200);
    Employee staff12 = new Employee(21, "1group", 1991, 11, 26, 1300);
    Employee staff13 = new Employee(13, "1group", 1992, 13, 27, 1400);

    Employee staff21 = new Employee(21, "2group", 1993, 11, 25, 2200);
    Employee staff22 = new Employee(22, "2group", 1994, 11, 26, 2300);
    Employee staff23 = new Employee(23, "2group", 1995, 12, 27, 2400);

    Employee staff31 = new Employee(21, "3group", 1996, 13, 25, 3200);
    Employee staff32 = new Employee(32, "3group", 1997, 11, 26, 3300);
    Employee staff33 = new Employee(33, "3group", 1998, 12, 27, 3400);
    List<Employee> staffs = new ArrayList<Employee>();
    staffs.add(staff11);
    staffs.add(staff12);
    staffs.add(staff13);
    staffs.add(staff21);
    staffs.add(staff22);
    staffs.add(staff23);
    staffs.add(staff31);
    staffs.add(staff32);
    staffs.add(staff33);
    long start = System.currentTimeMillis();
    GroupByList<Integer, Employee> groupByList = new GroupByList<Integer, Employee>();
    Map<Integer, List<Employee>> map = groupByList.groupBy(staffs, "month");
    for (Map.Entry<Integer, List<Employee>> entry : map.entrySet()) {
      List<Employee> eList = entry.getValue();

      System.out.println("组号为:" + entry.getKey());
      for (Employee employee : eList) {
        System.out.println(employee);
      }

    }
    long end = System.currentTimeMillis();
    System.out.println(end - start);
  }
}
Employee对象
package test;

import java.util.Date;

public class Employee {

  private Integer name;

  private String clazz;

  private Integer year;

  private Integer month;

  private Integer day;

  private double salary;

  public Employee() {
  };

  public Employee(Integer name, String clazz, Integer year, Integer month, Integer day,
      double salary) {
    super();
    this.name = name;
    this.clazz = clazz;
    this.year = year;
    this.month = month;
    this.day = day;
    this.salary = salary;
  }

  /**
   * @return name
   */
  public Integer getName() {
    return name;
  }

  /**
   * @return year
   */
  public Integer getYear() {
    return year;
  }

  /**
   * @return month
   */
  public Integer getMonth() {
    return month;
  }

  /**
   * @return day
   */
  public Integer getDay() {
    return day;
  }

  /**
   * @return salary
   */
  public double getSalary() {
    return salary;
  }

  /**
   * @param name
   *        set name
   */
  public void setName(Integer name) {
    this.name = name;
  }

  /**
   * @param year
   *        set year
   */
  public void setYear(Integer year) {
    this.year = year;
  }

  /**
   * @param month
   *        set month
   */
  public void setMonth(Integer month) {
    this.month = month;
  }

  /**
   * @param day
   *        set day
   */
  public void setDay(Integer day) {
    this.day = day;
  }

  /**
   * @param salary
   *        set salary
   */
  public void setSalary(double salary) {
    this.salary = salary;
  }

  /**
   * @return clazz
   */
  public String getClazz() {
    return clazz;
  }

  /**
   * @param clazz
   *        set clazz
   */
  public void setClazz(String clazz) {
    this.clazz = clazz;
  }

  @Override
  public String toString() {
    return "Employee [name=" + name + ", clazz=" + clazz + ", year=" + year + ", month=" + month
        + ", day=" + day + ", salary=" + salary + "]";
  }

}
要对JavaList进行分组,可以使用Map来实现。首先,定义一个Map对象,键为分组的标准,值为对应分组List。然后,遍历List中的元素,根据分组标准将元素放入对应的List中,最后将List放入Map中。 在Java 8中,可以使用Stream的groupingBy方法来快速实现List分组。通过Stream的collect方法结合Collectors的groupingBy静态方法,可以将List按照指定的属性进行分组。具体实现代码如下: ```java public Map<String, List<Student>> groupList(List<Student> students) { Map<String, List<Student>> map = students.stream() .collect(Collectors.groupingBy(Student::getName)); return map; } ``` 上述代码中,将List<Student>按照Student对象的name属性进行分组,最终返回一个Map<String, List<Student>>对象,键为学生姓名,值为对应姓名的学生列表。 另外,在Java 8之前的版本中,可以使用迭代List并通过判断来进行分组,具体实现代码如下: ```java public Map<String, List<Student>> groupList(List<Student> students) { Map<String, List<Student>> map = new HashMap<>(); for (Student student : students) { String name = student.getName(); if (!map.containsKey(name)) { map.put(name, new ArrayList<>()); } map.get(name).add(student); } return map; } ``` 上述代码中,通过遍历List<Student>,判断学生姓名是否已存在于Map中,如果不存在则创建一个新的空List,然后将学生对象添加到对应的List中。最终返回一个Map<String, List<Student>>对象,键为学生姓名,值为对应姓名的学生列表。 这两种方法都可以实现对List分组,具体选择哪种方法取决于你的需求和使用的Java版本。<span class="em">1</span><span class="em">2</span> #### 引用[.reference_title] - *1* [List分组的两种方式](https://blog.csdn.net/qq_36513313/article/details/122952747)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* [使用Java内部类实现一个简单的购物车系统.txt](https://download.csdn.net/download/weixin_44609920/88226617)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值