簡體   English   中英

從列表中打印不同的元素

[英]Printing distinct elements from a List

我創建了一個ArrayList ,其中包含不同人的ID 、姓名和年齡。 我應該只在控制台上打印不同的名稱,但我看到了許多列表是Stringint列表的示例,但沒有找到包含超過 1 條信息的列表的任何內容,例如我的情況. 如何只打印不同的名稱? 在下面的代碼中,我只想打印 Paul、Sabrina 和 Max)

主class

public class Main {
    public static void main(String[] args) {
        Person p1 = new Person(1, "Paul", 23);
        Person p2 = new Person(2, "Sabrina", 28);
        Person p3 = new Person(3, "Paul", 51);
        Person p4 = new Person(4, "Max", 34);
        Person p5 = new Person(5, "Paul", 31);

        ArrayList<Person> people = new ArrayList<>();
        people.add(p1);
        people.add(p2);
        people.add(p3);
        people.add(p4);
        people.add(p5);
    }
}

人 Class

public class Person {
    private int id;
    private String name;
    private int age;

    public Person(int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    @Override
    public String toString() {
        return "Id: " + this.id
                + ", Name: " + this.name
                + ", Age:" + this.age + "\n";
    }
}

最簡單的解決方案是使用 Set 來檢查您要打印的 Person 之前是否已經打印過它:

Set<String> temp = new HashSet<>();
for(Person p : people) {
    // True if was not printed before.
    if (temp.add(p.getName())) {
        System.out.println(p.getName());
    }
}

使用 Streams,您可以執行以下操作:

people.stream()
      .map(Person::getName)
      .collect(Collectors.toSet())
      .forEach(System.out::println);

有很多方法可以做到這一點,但它們都涉及相互檢查名稱是否重復。

可能最好的方法是將所有名稱添加到Set中,然后從那里打印出來。 就像是:

Set<String> distinctNames = new HashSet<>();

for (Person p : people) {
    
    distinctNames.add(p.getName());
}

for (String name : distinctNames) {

    ...
}

這里有一些關於Set概念的很好的文檔,但本質上它只是一個獨特元素的集合。

為此,您可以使用Stream#distinct方法:

people.stream()
        // take person's name
        .map(Person::getName)
        // only distinct names
        .distinct()
        // output line by line
        .forEach(System.out::println);

Output:

Paul
Sabrina
Max

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM