package cn.ziqirj.common.utils;
import lombok.Getter;
import lombok.Setter;
import java.util.ArrayList;
import java.util.List;
public class CustomOrderlyMap<T> {
@Getter
private List<String> keys = new ArrayList<>();
@Getter
private List<T> values = new ArrayList<>();
private List<map<T>> kv = new ArrayList<>();
public CustomOrderlyMap() {}
public void add(String key, T value) {
Integer index = getIndex(key);
if(null != index && index != -1) {
values.set(index, value);
kv.get(index).setValue(value);
return ;
}
keys.add(key);
values.add(value);
kv.add(new map<T>(key, value));
}
public void addAll(CustomOrderlyMap<T> customMap) {
if(null == customMap || customMap.size() == 0) {
return ;
}
List<map<T>> kvl = customMap.kv;
for(map<T> map : kvl) {
this.add(map.getKey(), map.getValue());
}
}
public void remove(String key) {
Integer index = getIndex(key);
if(null == index || index == -1 ) {
return ;
}
keys.remove(index);
values.remove(index);
kv.remove(index);
}
public void remove(T obj) {
Integer index = getIndex(obj);
if(null == index || index == -1 ) {
return ;
}
keys.remove(index);
values.remove(index);
kv.remove(index);
}
public void removeAll() {
this.keys = new ArrayList<>();
this.values = new ArrayList<>();
this.kv = new ArrayList<>();
}
public void close() {
this.keys.clear();
this.values.clear();
this.kv.clear();
}
public void set(String key, T value) {
Integer index = getIndex(key);
if(null == index || index.intValue() == -1)
return ;
values.set(index, value);
kv.get(index).setValue(value);
}
public T get(String key) {
Integer index = getIndex(key);
if (null == index || index == -1)
return null;
return kv.get(index).getValue();
}
public Integer size() {
return this.kv.size();
}
public boolean isEmpty() {
return this.kv.isEmpty();
}
public void print() {
if(isEmpty()) {
System.out.println("null");
}
System.out.print("CustomMap : [");
for(map<T> m : this.kv) {
System.out.print(m.toString());
}
System.out.println("]");
}
private Integer getIndex(String key) {
int length = this.keys.size();
if (length == 0) {
return -1;
}
for (int i = 0; i < length; i++) {
if (key.equals(keys.get(i))) {
return i;
}
}
return null;
}
private Integer getIndex(T t) {
int length = this.values.size();
if (length == 0) {
return -1;
}
for (int i = 0; i < length; i++) {
if (t.equals(values.get(i))) {
return i;
}
}
return null;
}
}
@Setter
@Getter
class map<T> {
private String key;
private T value;
public map(String key, T value) {
super();
this.key = key;
this.value = value;
}
@Override
public String toString() {
return "[K:" + key + " --> V:" + value + "]";
}
}