使用Java的distinct函数去除数组中重复的元素
Java中的distinct()函数是一个非常有用的函数,它可以去除数组中的重复元素。在Java中,数组是具有固定长度的容器,其中包含了一系列具有相同数据类型的元素。数组中的元素可以是任意类型,例如整数、字符串、对象等等。但是,有时候数组中会出现重复的元素,这时我们需要使用distinct()函数来将它们去除掉。
distinct()函数是Java 8中引入的新函数,它位于java.util.stream.Stream类中。该函数作用于一个流对象上,它返回一个包含去重后元素的新流对象。在实际应用中,我们通常先将数组转换为一个流对象,然后再使用distinct()函数去除重复元素。下面是一些示例代码,展示了如何使用distinct()函数去除数组中的重复元素。
1. 去除整型数组中的重复元素
int[] arr = new int[] {1, 2, 3, 4, 2, 3, 4, 5};
IntStream stream = Arrays.stream(arr);
IntStream distinctStream = stream.distinct();
int[] result = distinctStream.toArray();
System.out.println(Arrays.toString(result));
上述代码首先创建了一个整型数组arr,并利用Arrays类的stream()函数将其转换为一个流对象。然后使用distinct()函数去除重复元素,并将去重后的结果转换为一个新的整型数组result。最后,使用Arrays类的toString()函数将数组打印出来,其输出结果为[1, 2, 3, 4, 5]。
2. 去除字符串数组中的重复元素
String[] arr = new String[] {"Java", "C++", "Python", "C++", "Java"};
Stream<String> stream = Arrays.stream(arr);
Stream<String> distinctStream = stream.distinct();
String[] result = distinctStream.toArray(String[]::new);
System.out.println(Arrays.toString(result));
上述代码创建了一个字符串数组arr,使用Arrays类的stream()函数将其转换为一个流对象。然后使用distinct()函数去除重复元素,并使用toArray()函数将去重后的结果转换为一个新的字符串数组result。最后,使用Arrays类的toString()函数将数组打印出来,其输出结果为[Java, C++, Python]。
3. 去除自定义对象数组中的重复元素
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;
}
@Override
public boolean equals(Object obj) {
if(obj == this) {
return true;
}
if(!(obj instanceof Person)) {
return false;
}
Person other = (Person) obj;
return this.name.equals(other.name) && this.age == other.age;
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
}
Person[] arr = new Person[] {new Person("Tom", 20), new Person("Jerry", 22),
new Person("Tom", 20), new Person("Bob", 21)};
Stream<Person> stream = Arrays.stream(arr);
Stream<Person> distinctStream = stream.distinct();
Person[] result = distinctStream.toArray(Person[]::new);
System.out.println(Arrays.toString(result));
上述代码创建了一个Person类,表示一个人的姓名和年龄,并重写了equals()和hashCode()函数以实现对象的比较。然后创建了一个Person类型的数组arr,使用Arrays类的stream()函数将其转换为一个流对象。然后使用distinct()函数去除重复元素,并使用toArray()函数将去重后的结果转换为一个新的Person数组result。最后,使用Arrays类的toString()函数将数组打印出来,其输出结果为[Person{name='Tom', age=20}, Person{name='Jerry', age=22}, Person{name='Bob', age=21}]。
上述示例代码展示了如何使用Java的distinct()函数去除数组中的重复元素。无论是整型数组、字符串数组,还是自定义对象数组,都可以通过该函数轻松实现去重操作。
