在Scala.List和Java.util.List之间进行互操作

时间:2015-04-03 21:25:29

标签: java scala guava

我是Scala新手。我正在使用Google guava库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的方法?

2 个答案:

答案 0 :(得分:1)

更通俗地说,您可以尝试使用permutationsminBy

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

答案 1 :(得分:0)

正如Boris所指出的,permutation上的scala List方法可以直接使用,如下所示。

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