簡體   English   中英

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

[英]Interoperating between Scala.List and Java.util.List

我是Scala新手。 我正在使用谷歌番石榴庫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的方法中?

更習慣地說,您可以嘗試使用permutationsminBy

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

正如Boris在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
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM