在Java Map中按数字顺序重新定位键应该如何实现?

huangapple go评论49阅读模式
英文:

How to reposition keys by Number Order in Java Map?

问题

我正在尝试从Map中移除特定的键,并按索引重新定位所有键。例如:我的Map是这样的 Map<Integer,String>

0,"A"
1,"B"
2,"C"
3,"D"

如果我移除键1,那么输出应该是:

0,"A"
1,"C"
2,"D"

我如何保持键的索引顺序(从0到size-1),并在移除后为先前的键分配下一个值?

这是因为在将数据插入Map之前,我需要检查键是否存在。这种情况对我的recycler view adapter很重要,以保持唯一的位置,以避免重新加载已经存在于Map中的项目

英文:

I'm trying to remove a particular key from Map and reposition all keys index wise. For example: My map is like Map<Integer,String>

0,&quot;A&quot;
1,&quot;B&quot;
2,&quot;C&quot;
3,&quot;D&quot;

if i remove key 1 then output should be

0,&quot;A&quot;
1,&quot;C&quot;
2,&quot;D&quot;

How do i keep keys in index wise (0 to size-1) and assign next value to previous key after remove?

This is required because before insertion in map i need to check whether key exists or not. This scenario required for my recycler view adapter to hold unique positions to avoid reloading of items if exists in map

答案1

得分: 2

In your situation, if u want the index to be in that behavior. Map is not the answer. use List - can use ArrayList[insertion is often] or LinkedList[fast when reading].

Sample:

List<String> items = new ArrayList<>();
    
items.add("A");
items.add("B");
items add("C");
items add("D");

So if you remove index 1 or B;

items.remove(1);

The index of C will automatically be 1. Just like you wanted above.

英文:

In your situation, if u want the index to be in that behavior. Map is not the answer. use List - can use ArrayList[insertion is often] or LinkedList[fast when reading].

Sample:

List&lt;String&gt; items = new ArrayList&lt;&gt;();

items.add(&quot;A&quot;);
items.add(&quot;B&quot;);
items.add(&quot;C&quot;);
items.add(&quot;D&quot;);

So if you remove index 1 or B;

items.remove(1);

The index of C will automatically be 1. Just like you wanted above.

答案2

得分: 0

Maps 本质上没有顺序。没有办法在不将所有值从 Map 中取出并使用新键重新插入的情况下更改键。

听起来你可能更适合使用 List 而不是 Map。

ArrayList<String> strings = new ArrayList(Arrays.asList("A", "B", "C"));
// 0 => "A", 1 => "B", 2 => "C"
strings.remove(1);
// 0 => "A", 1 => "C"
英文:

Maps inherently have no order. There is no way to change the keys without taking all the values out of the Map and reinserting them with new keys.

It sounds like you may be better off using a List instead of a Map.

ArrayList&lt;String&gt; strings = new ArrayList(Arrays.asList(&quot;A&quot;, &quot;B&quot;, &quot;C&quot;));
// 0 =&gt; &quot;A&quot;, 1 =&gt; &quot;B&quot;, 2 =&gt; &quot;C&quot;
strings.remove(1);
// 0 =&gt; &quot;A&quot;, 1 =&gt; &quot;C&quot;

答案3

得分: 0

你不能通过更新键的值来在删除时排序键。在MAP中,更新键的唯一方法是删除键,然后重新插入带有新值的键。这很复杂且昂贵。建议你可以使用ArrayList来实现所需的结果。

英文:

You can't order the keys on deletion by updating key values. In MAP only way to update keys is removing the key and and re-insert it with new value. That is tricky and expensive. You can go with ArrayList for the desired result as suggested.

答案4

得分: 0

The TreeMap&lt;K,V&gt; 在 JDK 的 java.util 包中可以满足您的需求。无论您删除哪个键,排序都不会改变。

如果您想定义自己的排序方法,只需使用其自定义的 comparator 来覆盖构造方法 TreeMap(Comparator&lt;? super K&gt; comparator) 以实现键的排序。

public static void main(String[] args) {  
    Map&lt;Integer, String&gt; map = new TreeMap&lt;Integer, String&gt;();  
    map.put(0, &quot;A&quot;);
    map.put(1, &quot;B&quot;);
    map.put(2, &quot;C&quot;);
    map.put(3, &quot;D&quot;);
    // 无论您删除哪个键,排序都不会改变...
    for (Map.Entry&lt;Integer, String&gt; entry : resultMap.entrySet()) {  
        System.out.println(entry.getKey() + &quot; &quot; + entry.getValue());  
    }  
}  
英文:

The TreeMap&lt;K,V&gt; in the jdk java.util package can meet your needs. Whatever key you delete , the sort will never change.

If you want to define yourself sort method, just use its custom comparator to over-write construction method TreeMap(Comparator&lt;? super K&gt; comparator) to achieve key sorting.

public static void main(String[] args) {  
    Map&lt;Integer, String&gt; map = new TreeMap&lt;Integer, String&gt;();  
    map.put(0, &quot;A&quot;);
    map.put(1, &quot;B&quot;);
    map.put(2, &quot;C&quot;);
    map.put(3, &quot;D&quot;);
    // whatever key you delete , the sort will not change...
    for (Map.Entry&lt;Integer, String&gt; entry : resultMap.entrySet()) {  
        System.out.println(entry.getKey() + &quot; &quot; + entry.getValue());  
    }  
}  

答案5

得分: 0

You choose a very bad way to implement this in adapter but you can solve it with below code:

你选择了一种非常糟糕的方法来实现适配器,但你可以使用以下代码解决:

final Map<Integer, String> myStupidMap = new HashMap<>();
myStupidMap.put(1, "A");
myStupidMap.put(2, "B");
myStupidMap.put(3, "C");
myStupidMap.put(4, "D");

final int[] count = {0};
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
    myStupidMap.forEach(new BiConsumer<Integer, String>() {
        @Override
        public void accept(Integer integer, String s) {
            if (count[0] == 1){
                myStupidMap.remove(integer);
            }
            count[0]++;
        }
    });
}

我希望对你有用,但我建议不要使用这个地图。

英文:

you choose a very bad way to implement this in adapter
but you can solve it with below code:

 final Map&lt;Integer, String&gt; myStupidMap = new HashMap&lt;&gt;();
    myStupidMap.put(1, &quot;A&quot;);
    myStupidMap.put(2, &quot;B&quot;);
    myStupidMap.put(3, &quot;C&quot;);
    myStupidMap.put(4, &quot;D&quot;);

    final int[] count = {0};
    if (android.os.Build.VERSION.SDK_INT &gt;= android.os.Build.VERSION_CODES.N) {
        myStupidMap.forEach(new BiConsumer&lt;Integer, String&gt;() {
            @Override
            public void accept(Integer integer, String s) {
                if (count[0] == 1){
                    myStupidMap.remove(integer);
                }
                count[0]++;
            }
        });
    }

i hope useful for you But my suggestion is not to use the map.

huangapple
  • 本文由 发表于 2020年8月3日 12:22:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/63223696.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定