用JDK1.8list去重
时间: 2023-12-14 20:06:33 浏览: 16
可以使用Java8的Stream API进行列表去重,示例如下:
List<String> list = new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");
list.add("A");
List<String> distinctList = list.stream().distinct().collect(Collectors.toList());
System.out.println(distinctList); //输出结果:[A, B, C]
相关问题
jdk 1.8 List 去重
在 JDK 1.8 中,可以使用 Stream API 来对 List 进行去重操作。以下是一种常见的去重方法:
```java
List<T> list = new ArrayList<>(); // 原始的 List
List<T> distinctList = list.stream()
.distinct()
.collect(Collectors.toList());
```
上述代码中,假设你的 List 的泛型为 `T`,你可以将原始的 List 存储在 `list` 变量中。然后,通过调用 `stream()` 方法将 List 转换为 Stream 对象,接着使用 `distinct()` 方法对元素进行去重操作,最后使用 `collect()` 方法将结果转换回 List。
请注意,上述代码中的 `T` 是一个泛型,你需要将其替换为你实际使用的元素类型。另外,这种方法会保留第一个出现的元素,后续相同的元素将被忽略。如果你想要根据自定义的逻辑进行去重,可以使用 `distinct()` 方法的重载版本,并传入自定义的比较器。
jdk1.8 list分组
你可以使用Java 8中的Stream API来对List进行分组,以下是示例代码:
假设我们有一个Person类,其中包含姓名和年龄属性:
```
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
```
现在我们有一个Person对象的List,我们要按照年龄分组:
```
List<Person> persons = new ArrayList<>();
persons.add(new Person("Alice", 21));
persons.add(new Person("Bob", 22));
persons.add(new Person("Charlie", 21));
persons.add(new Person("Dave", 23));
persons.add(new Person("Eve", 22));
```
我们可以使用以下代码来按年龄分组:
```
Map<Integer, List<Person>> personsByAge = persons.stream()
.collect(Collectors.groupingBy(Person::getAge));
```
这个代码将会返回一个Map,其中键是年龄,值是该年龄的Person对象列表。你可以使用Map的get方法来获取特定年龄的人的列表。
如果你想按名称首字母分组,你可以使用以下代码:
```
Map<Character, List<Person>> personsByName = persons.stream()
.collect(Collectors.groupingBy(p -> p.getName().charAt(0)));
```
这个代码将会返回一个Map,其中键是名称的首字母,值是该首字母开头的Person对象列表。