[英]Create a TreeMap from nested list using Java Streams
Given: I have List<List<Integer>> locations
which is coordinates of a location. 给定:我有
List<List<Integer>> locations
,它是List<List<Integer>> locations
的坐标。 For example Place A: (2,4), Place B: (5,4), Place C: (10,9), Place D: (2,4). 例如,位置A:(2,4),位置B:(5,4),位置C:(10,9),位置D:(2,4)。 So my
locations
would contain of list of lists. 因此,我的
locations
将包含列表列表。 I am unable to change this format. 我无法更改此格式。
The cost to go to a specific location is the square root of the sum of the coordinates. 到达特定位置的成本是坐标总和的平方根。 So to go to the cost is
Place A = Math.sqrt(2 + 4)
, cost to go to Place B = Math.sqrt(5 + 4)
and so on. 因此,转到位置
Place A = Math.sqrt(2 + 4)
的成本为Place A = Math.sqrt(2 + 4)
,转到位置Place B = Math.sqrt(5 + 4)
成本为Place B = Math.sqrt(5 + 4)
,依此类推。
Output : What I'm trying to get is a list of the least 'cost' of all the locations. 输出 :我想要得到的是所有位置中最低“成本”的列表。 The requirement for the return is
List<List<Integer>> nearestLocations
. 返回的要求是
List<List<Integer>> nearestLocations
。 What I did is I'm trying to create a TreeMap<Double, List<List<Integer>>
我所做的是尝试创建
TreeMap<Double, List<List<Integer>>
Question my question is how do I convert the convert the below using Java 8 streams? 问我的问题是如何使用Java 8流转换下面的转换?
List<List<Integer>> findNearestLocation(int total, List<List<Integer>> allLocations, int size) {
ArrayList<List<Integer>> results = new ArrayList<>();
TreeMap<Double, List<Integer>> map = new TreeMap<>();
for (int i = 0; i < total && i < allLocations.size(); i++) {
List<Integer> list = allLocations.get(i);
double l = 0.0;
for (Integer x : list) {
l += x * x;
}
map.put(Math.sqrt(l), list);
}
if (map.size() > 0) {
for (int get = 0; get < size; get++) {
results.add(map.get(map.firstKey()));
map.remove(map.firstKey());
}
}
return results;
}
Your Map
is actually Map<Double, List<Integer>>
您的
Map
实际上是Map<Double, List<Integer>>
Your current code return just Map
if you want TreeMap
you need: 如果您需要
TreeMap
则当前代码仅返回Map
:
TreeMap<Double, List<List<Integer>>> x = locations.stream().collect(
Collectors.groupingBy((List<Integer> b) -> {
double d = b.stream().mapToDouble(i -> i.doubleValue()).sum();
return Math.sqrt(d);
},
TreeMap::new,
Collectors.toList()));
PS: You distance is not usual euclidean distance. PS:您的距离不是通常的欧几里得距离。 To make it so you need
i -> i.doubleValue() * i.doubleValue()
为此,您需要
i -> i.doubleValue() * i.doubleValue()
If you just want to sort that list by their distance, you can just do 如果您只想按他们的距离排序该列表,则可以
Collections.sort(list, (list1, list2) ->
Double.compare(Math.sqrt(list1.get(0) + list1.get(1)),
Math.sqrt(list2.get(0) + list2.get(1))));
or on a copy of the list if the initial list is immutable. 或列表的副本(如果初始列表是不可变的)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.