簡體   English   中英

Java:在“鏈接”列表中挑選多個元素

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

我有一個包含3個字符串和一個double的類的鏈接列表。 我想收集列表中每個雙精度值的總和。 例如

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

我想找到並加起來1.2和2.5。 我假設我應該使用ListIterator,但是如何告訴它將找到的每個double值加到總數中呢?

只需對人員使用for循環:

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

您有幾個選擇可以對其進行迭代

A)根據要求使用迭代器

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

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

B)按照其他答案中的建議使用for-each循環:

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

PS:強烈建議不要使用UPPERCASE來啟動Java變量或屬性

您可以遍歷列表,獲取每個Person的double屬性並對它們求和,或者可以使用Java 8 Streams:

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

其中getDoubleProperty代表Person類中返回雙getDoubleProperty值的方法的名稱。

暫無
暫無

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

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