gitee.com/lh-her-team/common@v1.5.1/linkedhashmap/linkedhashmap.go (about)

     1  package linkedhashmap
     2  
     3  import "container/list"
     4  
     5  type hashMapNode struct {
     6  	linklistNode *list.Element
     7  	val          interface{}
     8  }
     9  
    10  type LinkedHashMap struct {
    11  	linklist *list.List
    12  	hashmap  map[string]interface{}
    13  }
    14  
    15  func NewLinkedHashMap() *LinkedHashMap {
    16  	return &LinkedHashMap{
    17  		linklist: list.New(),
    18  		hashmap:  make(map[string]interface{}),
    19  	}
    20  }
    21  
    22  func (linkMap *LinkedHashMap) Add(key string, val interface{}) bool {
    23  	if _, isExists := linkMap.hashmap[key]; isExists {
    24  		return false
    25  	}
    26  	linkListNode := linkMap.linklist.PushBack(key)
    27  	linkMap.hashmap[key] = &hashMapNode{
    28  		linklistNode: linkListNode,
    29  		val:          val,
    30  	}
    31  	return true
    32  }
    33  
    34  func (linkMap *LinkedHashMap) Get(key string) interface{} {
    35  	originLinkedHashMapNode, isExists := linkMap.hashmap[key]
    36  	if !isExists {
    37  		return nil
    38  	}
    39  	return (originLinkedHashMapNode.(*hashMapNode)).val
    40  }
    41  
    42  func (linkMap *LinkedHashMap) Size() int {
    43  	return len(linkMap.hashmap)
    44  }
    45  
    46  func (linkMap *LinkedHashMap) Remove(key string) (bool, interface{}) {
    47  	originLinkedHashMapNode, isExists := linkMap.hashmap[key]
    48  	if !isExists {
    49  		return false, nil
    50  	}
    51  	linkedHashMapNode, _ := originLinkedHashMapNode.(*hashMapNode)
    52  	delete(linkMap.hashmap, key)
    53  	linkMap.linklist.Remove(linkedHashMapNode.linklistNode)
    54  	return true, linkedHashMapNode.val
    55  }
    56  
    57  func (linkMap *LinkedHashMap) GetLinkList() *list.List {
    58  	return linkMap.linklist
    59  }