Skip to content

Instantly share code, notes, and snippets.

@kevin-lee
Last active August 29, 2015 14:25
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save kevin-lee/ca610ef4ca9baa0b0366 to your computer and use it in GitHub Desktop.
Some Java 8 example code
package cc.kevinlee.examples;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import static cc.kevinlee.examples.KeyValPair.*;
/**
* @author Lee, Seong Hyun (Kevin)
* @since 2015-07-17
*/
public class SomeMapExample {
public static void main(final String[] args) {
final SomeMap<String, Integer> someMap = new SomeMap<>(new List[]{Arrays.asList(keyValPair("a", 1), keyValPair("b", 2), keyValPair("c", 3))});
System.out.println("someMap.contains a? " + someMap.containsKey("a")); // true
System.out.println("someMap.contains b? " + someMap.containsKey("b")); // true
System.out.println("someMap.contains c? " + someMap.containsKey("c")); // true
System.out.println("someMap.contains d? " + someMap.containsKey("d")); // false
final SomeMapWithNullableBucket<String, Integer> someMapWithNullableBucket = new SomeMapWithNullableBucket();
System.out.println(
"someMapWithNullableBucket.contains a? " + someMapWithNullableBucket.containsKey("a")
); // false
}
}
class KeyValPair<K, V> {
final K key;
final V value;
public KeyValPair(final K key, final V value) {
this.key = key;
this.value = value;
}
public K getKey() {
return key;
}
public V getValue() {
return value;
}
public static <K, V> KeyValPair<K, V> keyValPair(final K key, final V value) {
return new KeyValPair<>(key, value);
}
}
class SomeMap<K, V> {
private List<KeyValPair<K, V>>[] buckets;
public SomeMap(final List<KeyValPair<K, V>>[] buckets) {
this.buckets = buckets;
}
public boolean containsKey(final K k) {
return buckets[hash(k)].stream().map(KeyValPair::getKey).anyMatch(k::equals);
}
/**
* Dummy implemetation for testing. It always returns 0.
*
* @param k
* @return 0
*/
private int hash(final K k) {
return 0;
}
}
class SomeMapWithNullableBucket<K, V> {
private List<KeyValPair<K, V>>[] buckets;
public SomeMapWithNullableBucket() {
this.buckets = new List[1];
}
public boolean containsKey(final K k) {
return Optional.ofNullable(buckets[hash(k)])
.map(Collection::stream)
.filter(s -> s.map(KeyValPair::getKey).anyMatch(k::equals))
.isPresent();
// OR
// return Optional.ofNullable(buckets[hash(k)])
// .map(Collection::stream)
// .map(s -> s.map(KeyValPair::getKey))
// .map(s -> s.filter(k::equals))
// .flatMap(Stream::findAny)
// .isPresent();
// This one causes NullPointerException
// return buckets[hash(k)].stream().map(KeyValPair::getKey).anyMatch(k::equals);
}
/**
* Dummy implemetation for testing. It always returns 0.
*
* @param k
* @return 0
*/
private int hash(final K k) {
return 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment