代码之家  ›  专栏  ›  技术社区  ›  mel3kings

使用Java流创建嵌套列表中的树图

  •  0
  • mel3kings  · 技术社区  · 6 年前

    鉴于: 我有 List<List<Integer>> locations 这是一个位置的坐标。例如,放置A:(2,4),放置B:(5,4),放置C:(10,9),放置D:(2,4)。所以我的 locations 将包含个列表。 我无法更改此格式。

    到特定位置的成本是坐标和的平方根。所以要付出的代价是 Place A = Math.sqrt(2 + 4) 要花多少钱 Place B = Math.sqrt(5 + 4) 等等。

    产量 :我想得到的是所有地点中成本最低的一个列表。退货要求是 List<List<Integer>> nearestLocations . 我所做的是尝试创建一个 TreeMap<Double, List<List<Integer>>

    问题 我的问题是如何用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;
        }
    
    2 回复  |  直到 6 年前
        1
  •  2
  •   talex    6 年前

    你的 Map 实际上是 Map<Double, List<Integer>>

    你当前的代码返回只是 地图 如果你想要 TreeMap 你需要:

        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()));
    

    你的距离不是通常的欧几里得距离。为了满足你的需要 i -> i.doubleValue() * i.doubleValue()

        2
  •  1
  •   daniu    6 年前

    如果你只想按他们的距离排序,你可以这样做

    Collections.sort(list, (list1, list2) -> 
        Double.compare(Math.sqrt(list1.get(0) + list1.get(1)),
                       Math.sqrt(list2.get(0) + list2.get(1))));
    

    如果初始列表是不可变的,则在列表的副本上。