【问题标题】:Printing distinct elements from a List从列表中打印不同的元素
【发布时间】:2021-03-15 15:43:41
【问题描述】:

我创建了一个ArrayList,其中包含ID、不同人的姓名和年龄。我应该只在控制台上打印不同的名称,但我看到许多示例列表是 Stringint 列表,但没有找到包含超过 1 条信息的列表的任何内容就像我的情况一样。如何只打印不同的名称? (在下面的代码中,我只想打印 Paul、Sabrina 和 Max)

主类

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);
    }
}

人物类

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";
    }
}

【问题讨论】:

    标签: java arrays arraylist


    【解决方案1】:

    最简单的解决方案是使用 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);
    

    【讨论】:

      【解决方案2】:

      有很多方法可以做到这一点,但它们都涉及到相互检查名称是否重复。

      可能最好的方法是将所有名称添加到Set,然后从那里打印出来。比如:

      Set<String> distinctNames = new HashSet<>();
      
      for (Person p : people) {
          
          distinctNames.add(p.getName());
      }
      
      for (String name : distinctNames) {
      
          ...
      }
      

      关于Set 的概念有一些很好的文档here,但本质上它只是独特元素的集合。

      【讨论】:

        【解决方案3】:

        您可以为此目的使用Stream#distinct 方法:

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

        输出:

        Paul
        Sabrina
        Max
        

        【讨论】:

          猜你喜欢
          • 2011-10-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-02-07
          • 2018-07-22
          • 1970-01-01
          相关资源
          最近更新 更多