1 /*******************************************************************************
2 * Copyright (c) 2007, 2010 Association for Decentralized Information Management
4 * All rights reserved. This program and the accompanying materials
5 * are made available under the terms of the Eclipse Public License v1.0
6 * which accompanies this distribution, and is available at
7 * http://www.eclipse.org/legal/epl-v10.html
10 * VTT Technical Research Centre of Finland - initial API and implementation
11 *******************************************************************************/
12 package org.simantics.utils.datastructures;
14 import java.util.Collections;
15 import java.util.Comparator;
16 import java.util.HashMap;
17 import java.util.HashSet;
20 import java.util.TreeMap;
23 * MapSet is an associative data structure a key type on the left side (L) and a
24 * set element type of the right side.
27 * Based on {@link MapList} by Toni Kalajainen.
30 * @author Tuukka Lehtonen
32 public abstract class MapSet<L, R> {
34 protected Map<L, Set<R>> sets;
36 public static class Hash<L, R> extends MapSet<L, R> {
38 sets = new HashMap<L, Set<R>>();
40 protected Set<R> getOrCreateSet(L key) {
41 Set<R> set = sets.get(key);
43 set = new HashSet<R>();
50 public static class Tree<L, R> extends MapSet<L, R> {
52 sets = new TreeMap<L, Set<R>>();
54 public Tree(Comparator<? super L> comparator) {
55 sets = new TreeMap<L, Set<R>>(comparator);
57 protected Set<R> getOrCreateSet(L key) {
58 Set<R> set = sets.get(key);
60 set = new HashSet<R>();
67 public boolean add(L key, R value) {
68 Set<R> set = getOrCreateSet(key);
69 return set.add(value);
72 protected abstract Set<R> getOrCreateSet(L key);
74 private Set<R> getSet(L key) {
80 * @return a valid set, empty if no values exist
82 public Set<R> removeValues(L key) {
83 Set<R> set = sets.remove(key);
85 return Collections.emptySet();
89 public boolean remove(L key, R value) {
90 Set<R> set = getSet(key);
93 boolean result = set.remove(value);
103 public L[] getKeys(L[] list) {
104 return sets.keySet().toArray(list);
107 public Set<L> getKeys() {
108 return sets.keySet();
111 public boolean hasValues(L key) {
112 return sets.containsKey(key);
115 public R[] getValues(L key, R[] list) {
116 Set<R> l = sets.get(key);
119 return l.toArray(list);
122 public Set<R> getValues(L key) {
123 Set<R> l = sets.get(key);
126 return new HashSet<R>(l);
129 public Set<R> getValuesUnsafe(L key) {
130 return sets.get(key);