如何将以下代码转换为Java 8 Stream?

时间:2017-06-07 03:06:02

标签: java java-stream

我想知道是否可以将以下代码转换为Java 8 Stream?

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

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

理想的结构:

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

此问题来自教程,提示正在使用filtermap。我遇到的困难是如何在不启动空座List<Borg>的情况下添加元素。

2 个答案:

答案 0 :(得分:1)

或者更好一点:

    std::list<...> solutions;
    //i for distance1, j for distance2, z for distance3
    for (int i = 1; i < 101; i++) {

       for (int j = 1; j < 101; j++)  {

           for (int z = 1; z < 101; z++)  {

              evaluate if i, j, z satisfy EQ1, EQ2,EQ3
              if ( evaluate == true )
                solutions.push_back(...i,j,z...); //pseudocode

           }
       }

    }
// when all iterations are finished select a random from std::<list>

答案 1 :(得分:0)

以下是您的信息流的一小段代码。

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

}