简体   繁体   English

Java:在“链接”列表中挑选多个元素

[英]Java: Pick out multiple elements in Linked list

I have a linked list of classes which contain 3 strings and a double. 我有一个包含3个字符串和一个double的类的链接列表。 I want to collect the total value of each double in the list. 我想收集列表中每个双精度值的总和。 For example 例如

 LinkedList<Person> L = new LinkedList<Person>();
 Person p1 = new Person("Fee","Foo","Bar", 1.2);
 Person p2 = new Person("Fi","Fi","Fo", 2.5);
 L.add(p1);
 L.add(p2);

I would want to find and add up 1.2, and 2.5. 我想找到并加起来1.2和2.5。 I'm assuming I should use ListIterator, but how do I tell it to add each found double value to the total? 我假设我应该使用ListIterator,但是如何告诉它将找到的每个double值加到总数中呢?

Just use a for loop over the persons: 只需对人员使用for循环:

double sum = 0;
for(Person p : L)
    sum += p.getDouble();
System.out.print(sum);

You have couple of options to iterate over it 您有几个选择可以对其进行迭代

A) Using iterators as asked A)根据要求使用迭代器

Person person = new Person();
ListIterator<Person> listIterator = L.listIterator();

while (listIterator.hasNext()) {
      person = listIterator.next();
      double value = person.getDoubleAttribute();
}

B) Use a for-each loop as suggested in other answer: B)按照其他答案中的建议使用for-each循环:

for(Person person : L){
    double value = person.getDoubleAttribute();
}

PS: is highly discouraged to start Java variables or attributes by UPPERCASE PS:强烈建议不要使用UPPERCASE来启动Java变量或属性

You can iterate over the list, get the double property of each Person and sum them, or you can use Java 8 Streams : 您可以遍历列表,获取每个Person的double属性并对它们求和,或者可以使用Java 8 Streams:

double sum = L.stream().mapToDouble(Person::getDoubleProperty).sum();

Where getDoubleProperty stands for the name of a method in the Person class returning the double value. 其中getDoubleProperty代表Person类中返回双getDoubleProperty值的方法的名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM