java strem 获取list中的某一个字段 ,并且进行去重
- User
java strem 获取list中的某一个字段 ,并且进行去重
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
java strem 获取list中的某一个字段 ,并且进行去重
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
在 Java Stream 中获取 List 中某个字段的值并进行去重,主要会用到 map() 和 distinct() 这两个核心操作。
以下是一个详细的示例,包括一个自定义类、数据准备和不同情况的去重操作:
Product.java)首先,我们定义一个简单的 Product 类,它有 id、name 和 category 等字段。
import java.util.Objects;
public class Product {
private String id;
private String name;
private String category;
private double price;
public Product(String id, String name, String category, double price) {
this.id = id;
this.name = name;
this.category = category;
this.price = price;
}
// Getters
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getCategory() {
return category;
}
public double getPrice() {
return price;
}
@Override
public String toString() {
return "Product{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", category='" + category + '\'' +
", price=" + price +
'}';
}
// 通常在对象去重时会用到equals和hashCode,但这里我们是字段去重,所以不是必须的
// 不过,为了类的完整性,还是建议实现
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Product product = (Product) o;
return Double.compare(product.price, price) == 0 &&
Objects.equals(id, product.id) &&
Objects.equals(name, product.name) &&
Objects.equals(category, product.category);
}
@Override
public int hashCode() {
return Objects.hash(id, name, category, price);
}
}
StreamDeduplicationExample.java)在这个类中,我们将创建 Product 对象的 List,并演示如何提取和去重特定字段。
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
public class StreamDeduplicationExample {
public static void main(String[] args) {
// 1. 准备示例数据
List<Product> products = Arrays.asList(
new Product("P001", "Laptop A", "Electronics", 1200.0),
new Product("P002", "Mouse B", "Electronics", 25.0),
new Product("P003", "Keyboard C", "Electronics", 75.0),
new Product("P004", "Book D", "Books", 15.0),
new Product("P005", "Book E", "Books", 20.0),
new Product("P006", "Pen F", "Stationery", 5.0),
new Product("P007", "Notebook G", "Stationery", 10.0),
new Product("P008", "Tablet H", "Electronics", 800.0) // "Electronics" 再次出现
);
System.out.println("原始产品列表:");
products.forEach(System.out::println);
System.out.println("------------------------------------");
// 2. 获取所有不重复的分类名称 (Get distinct category names)
// 步骤:
// a. .stream(): 将List转换为Stream
// b. .map(Product::getCategory): 将每个Product对象映射(转换)为其分类字符串
// (Product::getCategory 是方法引用,等同于 p -> p.getCategory())
// c. .distinct(): 对流中的元素进行去重,只保留唯一的元素
// d. .collect(Collectors.toList()): 将去重后的元素收集回一个新的List中
List<String> distinctCategories = products.stream()
.map(Product::getCategory)
.distinct()
.collect(Collectors.toList());
System.out.println("不重复的分类名称 (Distinct Categories): " + distinctCategories);
System.out.println("------------------------------------");
// 3. 获取所有不重复的产品名称 (Get distinct product names)
// 假设产品名称也可能重复,比如不同的ID但是相同的名称
List<Product> productsWithNameDuplicates = Arrays.asList(
new Product("P101", "Chair A", "Furniture", 100.0),
new Product("P102", "Table B", "Furniture", 200.0),
new Product("P103", "Chair A", "Furniture", 110.0), // "Chair A" 再次出现
new Product("P104", "Desk C", "Office", 300.0)
);
System.out.println("包含重复名称的产品列表:");
productsWithNameDuplicates.forEach(System.out::println);
System.out.println("------------------------------------");
List<String> distinctProductNames = productsWithNameDuplicates.stream()
.map(Product::getName)
.distinct()
.collect(Collectors.toList());
System.out.println("不重复的产品名称 (Distinct Product Names): " + distinctProductNames);
System.out.println("------------------------------------");
// 4. 如果你不需要List,而只需要一个Set,可以更直接地使用Collectors.toSet()
// Set本身就是不包含重复元素的集合,因此它天然具有去重功能。
// 在这种情况下,distinct()操作可以是多余的(但无害)。
Set<String> distinctCategoriesSet = products.stream()
.map(Product::getCategory)
.collect(Collectors.toSet());
System.out.println("不重复的分类名称 (Collected to Set): " + distinctCategoriesSet);
}
}
原始产品列表:
Product{id='P001', name='Laptop A', category='Electronics', price=1200.0}
Product{id='P002', name='Mouse B', category='Electronics', price=25.0}
Product{id='P003', name='Keyboard C', category='Electronics', price=75.0}
Product{id='P004', name='Book D', category='Books', price=15.0}
Product{id='P005', name='Book E', category='Books', price=20.0}
Product{id='P006', name='Pen F', category='Stationery', price=5.0}
Product{id='P007', name='Notebook G', category='Stationery', price=10.0}
Product{id='P008', name='Tablet H', category='Electronics', price=800.0}
------------------------------------
不重复的分类名称 (Distinct Categories): [Electronics, Books, Stationery]
------------------------------------
包含重复名称的产品列表:
Product{id='P101', name='Chair A', category='Furniture', price=100.0}
Product{id='P102', name='Table B', category='Furniture', price=200.0}
Product{id='P103', name='Chair A', category='Furniture', price=110.0}
Product{id='P104', name='Desk C', category='Office', price=300.0}
------------------------------------
不重复的产品名称 (Distinct Product Names): [Chair A, Table B, Desk C]
------------------------------------
不重复的分类名称 (Collected to Set): [Books, Electronics, Stationery]
stream(): 将集合(如 List)转换为一个流,这是所有 Stream API 操作的起点。map(Product::getCategory): 这是一个中间操作。它会将流中的每一个 Product 对象,通过调用其 getCategory() 方法,转换成一个 String 类型的类别名称。此时,流中流动的就是一串字符串(可能包含重复)。distinct(): 这是一个中间操作。它会根据元素的 equals() 方法和 hashCode() 方法来判断元素是否重复,并只保留唯一的元素。对于 String 类型,它会正确地去重。collect(Collectors.toList()): 这是一个终止操作。它会将流中处理后的所有元素收集到一个新的 List 中。collect(Collectors.toSet()): 如果你最终需要一个 Set 而不是 List,并且对元素的顺序没有要求,那么直接使用 Collectors.toSet() 会更简洁。因为 Set 本身就不允许重复元素,所以它自然就达到了去重的目的,distinct() 操作在 toSet() 之前就变得冗余(尽管无害)。这种链式调用使得代码非常简洁和易读,是处理集合数据去重和转换的强大方式。