简体   繁体   中英

Java: Pick out multiple elements in Linked list

I have a linked list of classes which contain 3 strings and a 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. I'm assuming I should use ListIterator, but how do I tell it to add each found double value to the total?

Just use a for loop over the persons:

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

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:

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

PS: is highly discouraged to start Java variables or attributes by UPPERCASE

You can iterate over the list, get the double property of each Person and sum them, or you can use 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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