[英]How to reduce the list of doubles to string?
我是 java 8 和 Kotlin 中減少和折疊等功能方法的新手。我想減少 -
List<List<List<Double>>> boundingPolygon = [[[-125.48845080566404,47.94508483691371],[-124.96110705566404,42.309040799653665],[-117.13884143066404,45.04173793121063],[-118.36931018066404,48.93624688577435],[-125.48845080566404,47.94508483691371]]];
到表示一個由坐標連接的字符串的單個字符串 -
"-118.359053 33.931562,-118.372443 33.946939,-118.369053 33.951562,-118.337612 33.944342,-118.342012 33.944042,-118.359053 33.931562"
試圖做 -
val polygonCoordinates = boundingPolygon.first().reduce { acc, element ->
acc + "${element[0]} ${element[1]}"
}
這是行不通的。
reduce 操作中的acc
是List<Double>
類型,而不是String
類型。 看看 reduce function 簽名,你應該明白為什么了。 這是我建議做你想做的事情:
coords.first().joinToString(", ") { (x, y) -> "$x $y" }
我使用解構從坐標列表中提取第一個和第二個值。 所以這只適用於二維坐標。
與其減少它,不如將它們添加到StringBuilder
中,這在您進行多項操作時非常有效(例如連接大量字符串):
val boundingPolygon = listOf(
listOf(
listOf(-125.48845080566404, 47.94508483691371),
listOf(-124.96110705566404, 42.309040799653665),
listOf(-117.13884143066404, 45.04173793121063),
listOf(-118.36931018066404, 48.93624688577435),
listOf(-125.48845080566404, 47.94508483691371)
)
)
val sb = StringBuilder()
for (nestedList in boundingPolygon) {
for (innerNestedList in nestedList) {
sb.append(innerNestedList.joinToString(" "))
sb.append(',')
}
}
if (sb.isNotEmpty()) sb.deleteCharAt(sb.lastIndex)
println(sb)
// Output: -125.48845080566404 47.94508483691371,-124.96110705566404 42.309040799653665,-117.13884143066404 45.04173793121063,-118.36931018066404 48.93624688577435,-125.48845080566404 47.94508483691371
// val stringRepresentation = sb.toString() // for further use as String data-type
您可以使用flatMap代替 Reduce。 它會幫助你。
List<List<List<Double>>> boundingPolygon = List.of(List.of(List.of(-124.96110705566404, 42.309040799653665)
, List.of(-117.13884143066404, 45.04173793121063)
, List.of(118.36931018066404, 48.93624688577435)
));
var l = boundingPolygon.stream().flatMap(lists -> lists.stream().flatMap(doubles -> doubles.stream())).collect(Collectors.toList());
System.out.println(l);
它將打印如下所示的 output。
[-124.96110705566404, 42.309040799653665, -117.13884143066404, 45.04173793121063, 118.36931018066404, 48.93624688577435]
試試上面的代碼,這會對你有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.