Java tutorial
//package com.java2s; /* * Copyright 2015-2018 52North Initiative for Geospatial Open Source * Software GmbH * * 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. */ import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Optional; import java.util.stream.Collectors; public class Main { /** * @param <T> the element type * @param elements the elements * * @return an <b>UNMODIFIABLE</b> List<T> */ @SafeVarargs @SuppressWarnings("varargs") public static <T> List<T> list(T... elements) { return Collections.unmodifiableList(Arrays.asList(elements)); } /** * @param <T> the element type * @param l the list * * @return an <b>UNMODIFIABLE</b> List<T> */ public static <T> List<? extends T> unmodifiableList(List<? extends T> l) { return Optional.ofNullable(l).map(Collections::unmodifiableList).orElseGet(Collections::emptyList); } /** * @param entries * the <i>final</i> set of entries to add to the newly created * <i>unmodifiable</i> map * @param <K> the key type * @param <V> the value type * * @return an <i>unmodifiable</i> map with all given entries */ @SafeVarargs @SuppressWarnings("varargs") public static <K, V> Map<K, V> map(Entry<K, V>... entries) { return Collections .unmodifiableMap(Arrays.stream(entries).collect(Collectors.toMap(Entry::getKey, Entry::getValue))); } /** * @param <K> the key type * @param <V> the value type * @param m the map * * @return an <b>UNMODIFIABLE</b> Map<K, V> */ public static <K, V> Map<? extends K, ? extends V> unmodifiableMap(Map<? extends K, ? extends V> m) { return Optional.ofNullable(m).map(Collections::unmodifiableMap).orElseGet(Collections::emptyMap); } }