2 * Copyright (c) 2017. Developed by Hedgecode.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package org.hedgecode.snooker.json;
19 import java.io.Serializable;
20 import java.util.Collections;
21 import java.util.Comparator;
22 import java.util.Iterator;
23 import java.util.LinkedHashMap;
24 import java.util.LinkedList;
25 import java.util.List;
28 import org.hedgecode.snooker.api.CollectionEntity;
29 import org.hedgecode.snooker.api.IdEntity;
32 * Abstract Collection Entity to JSON deserialize.
34 * @author Dmitry Samoshin aka gotty
36 public abstract class JsonCollectionEntity<E extends IdEntity>
37 implements CollectionEntity<E>, Serializable
39 private final Map<Integer, E> entities = new LinkedHashMap<>();
41 protected JsonCollectionEntity(E[] entities) {
42 for (E entity : entities) {
45 entity.getId(), entity
50 protected JsonCollectionEntity(List<E> entities) {
51 for (E entity : entities) {
53 entity.getId(), entity
60 return entities.size();
64 public boolean isEmpty() {
65 return entities.isEmpty();
69 public Iterator<E> iterator() {
70 return entities.values().iterator();
74 public E byId(int id) {
75 return entities.get(id);
78 protected void sort(Comparator<E> comparator) {
79 List<E> entityList = new LinkedList<>(entities.values());
81 entityList, comparator
84 for (E entity : entityList) {
85 entities.put(entity.getId(), entity);
90 public void sortById() {
92 (entity1, entity2) -> entity1.getId() - entity2.getId()