Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.util.Iterator;
import java.util.LinkedHashMap;

import java.util.Map.Entry;

public class Main {
    public static <K, V> void putAt(LinkedHashMap<K, V> map, K key, V value, int pos) {
        Iterator<Entry<K, V>> ei = map.entrySet().iterator();
        LinkedHashMap<K, V> pre = new LinkedHashMap<>();
        LinkedHashMap<K, V> post = new LinkedHashMap<>();

        for (int i = 0; i < pos; i++) {
            if (!ei.hasNext())
                break;
            Entry<K, V> tmpE = ei.next();
            pre.put(tmpE.getKey(), tmpE.getValue());
        }
        // skip element at pos
        if (ei.hasNext())
            ei.next();
        while (ei.hasNext()) {
            Entry<K, V> tmpE = ei.next();
            post.put(tmpE.getKey(), tmpE.getValue());
        }

        map.clear();
        map.putAll(pre);
        map.put(key, value);
        map.putAll(post);
    }
}