java distinct list of objects

java distinct list of objects

how to remove person object with the same name in a list

/**
 * @author lautturi.com
 * Java example: distinct list objects by property of object
 */
import java.util.*;
import java.util.stream.Collectors;
class Person{
	String name;
	int age;
	
	public Person(String string, int i) {
		name = string;
		age = i;
	}

	public String getName() {
		return name;
	}
}
public class Lautturi {

	public static void main(String[] args) {
		List<Person> persons = new ArrayList<Person>();
		persons.add(new Person("Alan",13));
		persons.add(new Person("Bob",25));
		persons.add(new Person("James",22));
		persons.add(new Person("Tom",22));
		persons.add(new Person("Alan",23));

		Set<String> set = new HashSet<>(persons.size());
		
		persons = persons.stream().filter(p -> set.add(p.getName())).collect(Collectors.toList());
		
		for (Person p : persons) {
			System.out.print(p.getName()+" ");
		}
	}
}
Sour‮ec‬:www.lautturi.com

output:

Alan Bob James Tom
Created Time:2017-09-18 15:04:18  Author:lautturi