如何使用Stream Java 8并行化java程序

时间:2017-12-03 17:34:19

标签: java multithreading arraylist java-8

地狱中的每个人,

我创建了一个简化的程序来向您展示我愿意做的事情。 我们的想法是在每个顶点之间创建一个边缘。

Class Vertex

public class Vertex {
    private String sequence = new String();

    public Vertex() {
    }

    public Vertex(String seq) {
        this.sequence = seq;
    }

    @Override
    public String toString() {
        return this.sequence.toString();
    }
}

班级边缘

public class Edge {

    private Vertex source;
    private Vertex destination;
    private int weight;

    public Edge() {

    }

    public Edge(Vertex source, Vertex destination, int weight) {
        this.source = source;
        this.destination = destination;
        this.weight = weight;

    }
}

致电计划

public class Example {


    public static void main(String[] args) {

            ArrayList <Vertex> listOfVertex = new ArrayList<>();
            listOfVertex.add(new Vertex("One"));
            listOfVertex.add(new Vertex("Two"));
            listOfVertex.add(new Vertex("Three"));

            ArrayList <Edge> listOfEdges = new ArrayList<>();
            for (int i = 0; i < 3; i++) {
                for (int j = 0; j < 3; j++) {
                    if (i==j)
                        continue;
                    int weight = new Random().nextInt();
                    Edge edge = new Edge(listOfVertex.get(i), listOfVertex.get(j),weight);
                    listOfEdges.add(edge);
                }
            }
      }
}

通常在此步骤中边缘列表应

  • Edge 1:one Two
  • Edge 2:one Three
  • Edge 3:Two One
  • Edge 4:Two Three
  • Edge 5:Three One
  • Edge 6:Three Two

如何使用Java Stream来使用多线程? 我全天搜索了解Java 8 for stream的语法,但这很困难。

1 个答案:

答案 0 :(得分:3)

这里没有理由使用多线程。如果你有数百个顶点,也许吧。但无论如何:

List<Edge> edges = listOfVertex.parallelStream()
    .flatMap(v1 -> listOfVertex.stream()
                               .filter(v2 -> v2 != v1)
                               .map(v2 -> createEdge(v1, v2)))
    .collect(Collectors.toList());