Scala.List 和 Java.util.List 之间的互操作

Interoperating between Scala.List and Java.util.List

我是 Scala 新手。我正在使用 Google 番石榴库 Collections2.permutations() 方法,该方法将 java.util.Collection collection

作为输入

我有以下代码,改编自我编写的相应 Java 程序。

import java.util

import com.google.common.collect.Collections2
import collection.JavaConversions._

class OptimalTSP {

  def distance(point1: Point, point2: Point): Double = {
      Math.sqrt(Math.pow(point2.y - point1.y, 2) + Math.pow(point2.x - point1.x, 2))
    }

    def findCheapestPermutation(points: java.util.List[Point]): java.util.List[Point] = {
      var cost: Double = Double.MaxValue
      var minCostPermutation: java.util.List[Point] = null
      val permutations: util.Collection[java.util.List[Point]] = Collections2.permutations(points)
      import scala.collection.JavaConversions._
      for (permutation <- permutations) {
        val permutationCost: Double = findCost(permutation)
        if (permutationCost <= cost) {
          cost = permutationCost
          minCostPermutation = permutation
        }
      }
      println("Cheapest distance: " + cost)
      minCostPermutation
    }
 }

以上工作正常,但明确需要完整的包名称 java.util.List。是否有更惯用的 scala 方法来执行此操作,即将 scala List 传递到期望 Java Collection?

的方法中

正如鲍里斯在scala List上的评论permutation方法中指出的那样,可以直接使用,如下所示。

class OptimalTSP {

  def distance(point1: Point, point2: Point): Double = {
      Math.sqrt(Math.pow(point2.y - point1.y, 2) + Math.pow(point2.x - point1.x, 2))
    }

  def findCheapestPermutation(points: List[Point]): List[Point] = {
    var cost: Double = Double.MaxValue
    var minCostPermutation: List[Point] = null
    for (permutation <- points.permutations) {
      val permutationCost: Double = findCost(permutation)
      if (permutationCost <= cost) {
        cost = permutationCost
        minCostPermutation = permutation
      }
    }
    println("Cheapest distance: " + cost)
    minCostPermutation
  }
}

更习惯地说,您可以尝试使用 permutationsminBy:

 points.permutations.minBy(permutation => findCost(permutation))
 points.permutations.minBy(findCost) //equivalent