小编Ala*_*ook的帖子

在Java中深度生成列表n层的所有组合

我正在使用以下代码来生成大小为s的组合的列表:

public static <T extends Comparable<? super T>> List<List<T>> combinations(List<T> items, int size) {
        if (size == 1) {
            List<List<T>> result = new ArrayList<>();
            for (T item : items) {
                result.add(Collections.singletonList(item));
            }
            return result ;
        }
        List<List<T>> result = new ArrayList<>();
        for (int i=0; i <= items.size() - size; i++) {
            T firstItem = items.get(i);
            List<List<T>> additionalItems = combinations(items.subList(i+1, items.size()), size-1) ;
            for (List<T> additional : additionalItems) {
                List<T> combination = new ArrayList<>();
                combination.add(firstItem);
                combination.addAll(additional);
                result.add(combination);
            }
        }
        return result …
Run Code Online (Sandbox Code Playgroud)

java algorithm math combinations combinatorics

6
推荐指数
1
解决办法
312
查看次数

按键升序对地图进行排序

我正在尝试根据键按升序对地图进行排序。鉴于Map

Map<Integer, String> map = new LinkedHashMap<Integer, String>();

map.put(5, "five");
map.put(1, "one");
map.put(3, "three");
map.put(0, "zero");
Run Code Online (Sandbox Code Playgroud)

我想要订单:

0, zero
1, one
3, three
5, five
Run Code Online (Sandbox Code Playgroud)

我编写了以下代码来完成此任务:

    public <K, V extends Comparable<? super V>> Map<K, V> sortByKeyInAscendingOrder(Map<K, V> map)
{
    List<Entry<K, V>> list = new ArrayList<>(map.entrySet());
    list.sort(Entry.comparingByKey());

    Map<K, V> result = new LinkedHashMap<>();
    for (Entry<K, V> entry : list) {
        result.put(entry.getKey(), entry.getValue());
    }
    return result;
}
Run Code Online (Sandbox Code Playgroud)

但是,当我打电话时sort(),出现以下错误:

The method sort(Comparator<? super Map.Entry<K,V>>) in the type List<Map.Entry<K,V>> is …
Run Code Online (Sandbox Code Playgroud)

java sorting hashmap map-function

5
推荐指数
1
解决办法
2037
查看次数