从类对象创建ArrayList有更简单的方法吗?

huangapple go评论72阅读模式
英文:

ArrayList from class objects simpler way to do?

问题

我知道如何将类对象放入 Java 的 ArrayList 中(因为新对象可以附加而无需首先知道索引),但我想知道是否有一种更简单的方法将它们添加到 ArrayList 并对它们进行迭代?

我甚至在思考,假设我将对象名称保持在某种模式中,我应该能够使用循环将每个对象添加到列表中,例如 car1, car2, car3, ...

import java.util.ArrayList;

public class TestCar {
        
    public static void main(String[] args) {
        ArrayList<String> carNames = new ArrayList<>();
        // Cars have simple getter methods corresponding with String and int
        Car car1 = new Car("Rav4", 2017);
        carNames.add(car1.getName());
        Car car2 = new Car("Commodore", 2005);
        carNames.add(car2.getName());

        for (int i = 0; i < carNames.size(); i++) {
            System.out.println(carNames.get(i));
        }

    }
}

一如既往,感谢任何回复!

英文:

I know how to put class objects to an ArrayList in java (since new objects can be appended without knowledge of an index first) but I was wondering if there is a simpler way of adding them to an ArrayList and iterating over them?

I was even thinking that, hypothetically, if I kept my object names in a pattern, that I should be able to add each object to the list using a loop e.g. car1, car2, car3, ...

import java.util.ArrayList;

public class TestCar {
        
    public static void main(String[] args) {
        ArrayList&lt;String&gt; carNames = new ArrayList&lt;&gt;();
        // Cars have simple getter methods corresponding with String and int
        Car car1 = new Car(&quot;Rav4&quot;, 2017);
        carNames.add(car1.getName());
        Car car2 = new Car(&quot;Commodore&quot;, 2005);
        carNames.add(car2.getName());

        for (int i = 0; i &lt; carNames.size(); i++) {
            System.out.println(carNames.get(i));
        }

    }
}

As always, thanks for any replies!

答案1

得分: 1

假设您正在使用Java 8或更高版本,您可以将您的Car对象添加到一个列表中,并使用流来获取carNames列表:

List<Car> myCarList = Arrays.asList(new Car("Rav4", 2017), new Car("Commodore", 2005));
List<String> carNames = myCarList.stream()
                                 .map(Car::getName)
                                 .collect(Collectors.toList());
英文:

Assuming you are using Java 8 or higher, you could add your Car objects to a list and use streams to get a list of carNames :

List&lt;Car&gt; myCarList = Arrays.asList( new Car(&quot;Rav4&quot;, 2017), new Car(&quot;Commodore&quot;, 2005));
List&lt;String&gt; carNames = myCarList.stream()
                                 .map(Car::getName)
                                 .collect(Collectors.toList());

huangapple
  • 本文由 发表于 2020年9月22日 15:10:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/64004697.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定