GabrielChu
GabrielChu

Reputation: 6156

How to convert the following code to Java 8 Stream?

I was wondered if it is possible to convert the following code to Java 8 Stream?

List<Borg> newBorgMembers = new ArrayList<>();

// mankind is a List<Individual>
mankind.forEach(id -> newBorgMembers.add(new Borg(id)));

Desired structure:

List<Borg> newBorgMembers = mankind.stream().filter().map().collect()

This question is from a tutorial, the hints are using filter and map. The difficulty to me is that how to add elements without initiate an empty holder List<Borg>.

Upvotes: 0

Views: 87

Answers (2)

Eugene
Eugene

Reputation: 120848

Or a little bit nicer:

 mankind.stream()
        .map(Individual::getId)
        .map(Borg::new)
        .collect(Collectors.toList());

Upvotes: 1

Dau Zi
Dau Zi

Reputation: 320

Here is a small piece of code for your stream.

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class StreamTest {

    public static void main(String[] args) {
        // Initialize mankind
        List<Individual> mankind = new ArrayList<>();
        mankind.add(new Individual("A"));
        mankind.add(new Individual("B"));
        mankind.add(new Individual("C"));


        // The stream
        List<Borg> newBorgMembers = mankind.stream().map(individual -> new Borg(individual.id)).collect(Collectors.toList());

        newBorgMembers.forEach(borg -> System.out.println(borg.id));
    }
}

class Individual {
    String id;
    public Individual(String id) {
        this.id = id;
    }


}
class Borg {
    String id;

    public Borg(String id) {
        this.id = id;
    }

}

Upvotes: 0

Related Questions