/* * Copyright (c) 2017. Developed by Hedgecode. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.hedgecode.snooker.json; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.hedgecode.snooker.api.CollectionEntity; import org.hedgecode.snooker.api.IdEntity; /** * Abstract Collection Entity to JSON deserialize. * * @author Dmitry Samoshin aka gotty */ public abstract class JsonCollectionEntity implements CollectionEntity, JsonSerializable { private final Map entities = new LinkedHashMap<>(); protected JsonCollectionEntity(E[] entities) { for (E entity : entities) { if (entity != null) this.entities.put(entity.getId(), entity); } } protected JsonCollectionEntity(List entities) { for (E entity : entities) { this.entities.put(entity.getId(), entity); } } @Override public int size() { return entities.size(); } @Override public boolean isEmpty() { return entities.isEmpty(); } @Override public Iterator iterator() { return entities.values().iterator(); } @Override public E byId(int id) { return entities.get(id); } protected void sort(Comparator comparator) { List entityList = new LinkedList<>(entities.values()); Collections.sort( entityList, comparator ); entities.clear(); for (E entity : entityList) { entities.put(entity.getId(), entity); } } @Override public void sortById() { sort( (entity1, entity2) -> entity1.getId() - entity2.getId() ); } }