001/* 002 * oauth2-oidc-sdk 003 * 004 * Copyright 2012-2016, Connect2id Ltd and contributors. 005 * 006 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use 007 * this file except in compliance with the License. You may obtain a copy of the 008 * License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, software distributed 013 * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 014 * CONDITIONS OF ANY KIND, either express or implied. See the License for the 015 * specific language governing permissions and limitations under the License. 016 */ 017 018package com.nimbusds.oauth2.sdk.util; 019 020 021import java.util.HashMap; 022import java.util.List; 023import java.util.Map; 024 025 026/** 027 * Multi-valued map utilities. 028 */ 029public final class MultivaluedMapUtils { 030 031 032 /** 033 * Converts the specified multi-valued map to a single-valued map by 034 * taking the first value in the list. 035 * 036 * @param map The multi-valued map, {@code null} if not specified. 037 * 038 * @return The single-valued map, {@code null} if no map was specified. 039 */ 040 public static <K,V> Map<K,V> toSingleValuedMap(final Map<K,List<V>> map) { 041 042 if (map == null) 043 return null; 044 045 Map<K,V> out = new HashMap<>(); 046 047 for (Map.Entry<K,List<V>> en: map.entrySet()) { 048 049 if (en.getValue() == null || en.getValue().isEmpty()) { 050 out.put(en.getKey(), null); 051 } else { 052 out.put(en.getKey(), en.getValue().get(0)); 053 } 054 } 055 056 return out; 057 } 058 059 060 /** 061 * Gets the first value for the specified key. 062 * 063 * @param map The multi-valued map. Must not be {@code null}. 064 * @param key The key. Must not be {@code null}. 065 * 066 * @return The first value, {@code null} if not set. 067 */ 068 public static <K,V> V getFirstValue(final Map<K,List<V>> map, final K key) { 069 070 List<V> valueList = map.get(key); 071 072 if (valueList == null || valueList.isEmpty()) { 073 return null; 074 } 075 076 return valueList.get(0); 077 } 078 079 080 /** 081 * Removes the entry for the specified key and returns its first value. 082 * 083 * @param map The multi-valued map. Must not be {@code null}. 084 * @param key The key. Must not be {@code null}. 085 * 086 * @return The first value, {@code null} if not set. 087 */ 088 public static <K,V> V removeAndReturnFirstValue(final Map<K,List<V>> map, final String key) { 089 090 List<V> valueList = map.remove(key); 091 092 if (valueList == null || valueList.isEmpty()) { 093 return null; 094 } 095 096 return valueList.get(0); 097 } 098 099 100 /** 101 * Prevents public instantiation. 102 */ 103 private MultivaluedMapUtils() {} 104}