Created
April 17, 2014 02:41
-
-
Save avshabanov/10949276 to your computer and use it in GitHub Desktop.
Sequences.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.truward.polymer.util; | |
import com.google.common.collect.ImmutableList; | |
import com.google.common.collect.ImmutableMap; | |
import com.google.common.collect.ImmutableSet; | |
import javax.annotation.Nonnull; | |
import java.util.*; | |
/** | |
* Static utility methods for working with collections. | |
* Defines a set of | |
* | |
* @author Alexander Shabanov | |
*/ | |
public final class Sequences { | |
/** Hidden */ | |
private Sequences() {} | |
@Nonnull public static <T> List<T> join(@Nonnull List<? extends T> source, @Nonnull T element) { | |
final int size = source.size(); | |
if (size == 0) { | |
return ImmutableList.of(element); | |
} else if (size == 1) { | |
return ImmutableList.of(source.get(0), element); | |
} | |
// non-cheap operation - make list | |
final List<T> result = new ArrayList<>(size + 1); | |
result.addAll(source); | |
result.add(element); | |
return ImmutableList.copyOf(result); | |
} | |
@Nonnull public static <T> Set<T> join(@Nonnull Set<? extends T> source, @Nonnull T element) { | |
final int size = source.size(); | |
if (size == 0) { | |
return ImmutableSet.of(element); | |
} | |
// non-cheap operation - make list | |
final List<T> result = new ArrayList<>(size + 1); | |
result.addAll(source); | |
result.add(element); | |
return ImmutableSet.copyOf(result); | |
} | |
@Nonnull public static <K, V> Map<K, V> join(@Nonnull Map<? extends K, ? extends V> source, | |
@Nonnull K key, | |
@Nonnull V value) { | |
final int size = source.size(); | |
if (size == 0) { | |
return ImmutableMap.of(key, value); | |
} | |
// non-cheap operation - make list | |
final Map<K, V> result = new LinkedHashMap<>(); | |
result.putAll(source); | |
result.put(key, value); | |
return ImmutableMap.copyOf(result); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment