gpt-3.5-turbo-0301· OpenAI
WildChat-4.8M (AI2)
ArrayList 对象 如何分组?
- User
ArrayList 对象 如何分组?
- Assistant
在 ArrayList 中进行分组,可以使用 Java 8 中提供的 stream API 来进行操作。以下是一个示例代码:
假设我们有一个 ArrayList,包含了一些 Person 对象。现在要根据他们的年龄进行分组,将年龄相同的人放在同一个组中。
class Person { String name; int age; public Person(String name, int age) { this.name = name; this.age = age; } public int getAge() { return age; } } ArrayList<Person> people = new ArrayList<>(); people.add(new Person("Joe", 20)); people.add(new Person("Jane", 21)); people.add(new Person("John", 20)); people.add(new Person("Jack", 22));现在,我们可以使用 stream API 进行分组:
Map<Integer, List<Person>> groupedPeople = people.stream().collect(Collectors.groupingBy(Person::getAge)); groupedPeople.forEach((age, persons) -> { System.out.println("Age: " + age); persons.forEach(person -> System.out.println(" " + person.name)); });上面的代码中,
groupingBy方法接收一个 lambda 表达式,指定按照哪个字段进行分组。这里我们使用了Person::getAge,即按照年龄进行分组。最终得到的groupedPeople就是一个 Map 对象,其中 key 是年龄,value 是年龄相同的 Person 对象的 List。输出的结果是:
Age: 20 Joe John Age: 21 Jane Age: 22 Jack可以看到,年龄相同的人被分到了同一个组中。