I am having hard time using streaming API in Java for generics map. I have a map which extends LinkedHashMap in the following way
public class LRUCache<K, V> extends LinkedHashMap<K, V> {
private int size;
public LRUCache(int size) {
super(size);
this.size = size;
}
#Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > size;
}
public LRUCache<K, V> collect() {
return entrySet()
.stream()
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)
);
}
}
I am experimenting with a dummy method collect which will actually stream on the entrySet, apply some filters on it and then return a new LRUCache, but Collectors.toMap keep throwing an error which says
"Non-static method cannot be referenced from a static context"
I know this is some issue with Collectors.toMap generics definition. But, I am not able to figure out the right generics to get rid of the error and achieve the streaming and collecting functionality
LinkedHashMap includes in its implementation is a no-argument constructor that acts as a supplier to the toMap collect operation. You can introduce the same as well by including:
public LRUCache() {
this(10); // default size
}
Thereafter you can collect the LRUCache implementation using the toMap override with LRUCache::new supplier in the following manner:
public LRUCache<K, V> collect() {
return entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey,
Map.Entry::getValue,
(a, b) -> a, LRUCache::new));
}
Note:- That what matters is providing a supplier to collect to a different implementation than a HashMap which is what you get using the other overloaded implementation of toMap.
You appear simply to be trying to copy your map/cache. There is no need for streams to do this.
Add a (maybe private) constructor, which invokes the map copy constructor:
private LRUCache(Map<K, V> map, int size) {
super(map);
this.size = size;
}
Then just use this in your collect method:
public LRUCache<K, V> collect() {
return new LRUCache<>(this, size);
}
Or, without adding the constructor:
public LRUCache<K, V> collect() {
LRUCache<K, V> copy = new LRUCache<>(size);
copy.putAll(this);
return copy;
}
Related
I've spent many years working with Java 1.6 (maintaining legacy tools) and am just starting to migrate to 1.8. One big change is the functional methods in the java.util.Collections suite. The biggest concern for me is I have several collection extensions which apply careful checks or algorithms on modification. Do the default methods call the already defined put(..), get(...), remove(..) etc functions or do I have to do a major rework to make this work?
E.g. (ignoring null checks, etc. map that only holds values <= 10)
public class LimitedMap extends HashMap<String, Integer>{
#Override
public Integer put(String key, Integer value){
if(value> 10) throw new IllegalArgumentException();
return super.put(key, value);
}
#Override
public Integer computeIfAbsent(String key, Function<? super String, ? extends Integer> mappingFunction) {
return super.computeIfAbsent(key, mappingFunction);
}
}
With this pair of functions: would I still have to do a detailed override and put new checks into the computeIfAbsent function?
The only way you could be certain that only the interface methods from pre Java 8 can be used is if you somehow could delegate to the default method implementation in the interface (Map<K, V> in this case).
That is, if you could write something like the following (which you can't).
public class LimitedMap extends HashMap<String, Integer> {
#Override
public Integer computeIfAbsent(String key,
Function<? super String, ? extends Integer> mappingFunction) {
return Map.super.computeIfAbsent(key, mappingFunction);
}
}
Unfortunately that is not legal since you only can invoke the method that you've overriden (here the one from HashMap<String, Integer>) but not the one which the inherited method might have overridden (these are the normal rules for super method invocation).
So the only workaround I see for your situation is to create a copy of the interface default method implementation in a helper class like this:
public class Maps {
public static <K, V> V computeIfAbsent(Map<K, V> map,
K key, Function<? super K, ? extends V> mappingFunction) {
Objects.requireNonNull(mappingFunction);
V v;
if ((v = map.get(key)) == null) {
V newValue;
if ((newValue = mappingFunction.apply(key)) != null) {
map.put(key, newValue);
return newValue;
}
}
return v;
}
}
This is the implementation from java.util.Map as a static method enhanced by an additional parameter map for the instance to operate on.
With such a helper class you could now write
public class LimitedMap extends HashMap<String, Integer> {
#Override
public Integer computeIfAbsent(String key,
Function<? super String, ? extends Integer> mappingFunction) {
return Maps.computeIfAbsent(this, key, mappingFunction);
}
}
That's not the prettiest solution but one that should work with a limited amount of effort.
I have a data model that looks like this:
class CustomField {
String key;
String value;
}
From an API that I can get instances of List<CustomField>. The keys are unique in the list, which means that this collection really should be a Map<String, String>. Operating on this list is a pain, since every operation requires iteration to check for existing keys (CustomField doesn't implement equals either)
How can I create a Map<String, String> "view" backed by this list, so that I can operate on it using the Map interface?
I want a generic method like: <T, K, V> Map<K, V> createMapBackedByList(List<T> list, BiFunction<K, V, T> elementMapper, Function<T, K> keyMapper, Function<T, V> valueMapper) or similar.
It would use the functions to map between the list elements and map keys and values.
The important thing here is that I want changes to the map to be reflected in the underlying list, which is why the Streams API does not work here...
EDIT: I can't modify the API or the CustomField class.
Simple:
Write your own
public class ListBackedMap<K, V> implements Map<K, V> {
which takes some sort of List<Pair<K,V>> on creation; and "defers" to that. Of course, that requires that your CustomField class implements that Pair interface. (which you would probably need to invent, too)
( alternatively: your new class extends AbstractMap<K,V> to safe you most of the work ).
And now your methods simply return an instance of such a Map.
In other words: I am not aware of a built-in wrapper that meets your requirements. But implementing one yourself should be pretty straight forward.
Edit: given the fact that the OP can't change the CustomField class, a simple helper such as
interface <K, V> MapEntryAdapter {
K getKey();
V getValue();
}
would be required; together with a specific implementation that knows how to retrieve key/value from an instance of CustomField. In this case, the map would be backed by a List<MapEntryAdapter<K, V>> instead.
I ended up trying to implement it myself and basing it on an AbstractList. It was actually easier than I first though...
public class ListBackedMap<T, K, V> extends AbstractMap<K, V> {
private final List<T> list;
private final BiFunction<K, V, T> keyValueToElement;
private final Function<T, K> elementToKey;
private final Function<T, V> elementToValue;
public ListBackedMap(List<T> list, BiFunction<K, V, T> keyValueToElement, Function<T, K> elementToKey, Function<T, V> elementToValue) {
this.list = list;
this.keyValueToElement = keyValueToElement;
this.elementToKey = elementToKey;
this.elementToValue = elementToValue;
}
#Override
public Set<Entry<K, V>> entrySet() {
return list.stream()
.collect(toMap(elementToKey, elementToValue))
.entrySet();
}
#Override
public V put(K key, V value) {
V previousValue = remove(key);
list.add(keyValueToElement.apply(key, value));
return previousValue;
}
public List<T> getList() {
return list;
}
}
It's not very performant (or thread safe), but it seems to do the job well enough.
Example:
List<CustomField> list = getList();
ListBackedMap<CustomField, String, String> map = new ListBackedMap<>(
list,
(key, value) -> new CustomField(key, value),
CustomField::getKey,
CustomField::getValue);
I have a task where I need to implement some functionallity to abstract methods. The idea is to use Java 8, but I'm kinda new to programming with Java 8. The following is the abstract class that I need to implement:
public abstract class SortedMap<K extends Comparable<K>, V> implements Iterable<Pair<K, V>>
{
/**
* Returns a map where all values have been translated using the function
* <code>f</code>.
*/
public abstract <C> SortedMap<K, C> map(Function<? super V, ? extends C> f);
/**
* Returns a map containing only the keys that satisfies
* the predicate <code>p</code>.
*/
public abstract SortedMap<K, V> filter(Predicate<? super K> p);
// ...
}
What I've got so far (with Java 8) is:
public final class SortedMapImpl<K extends Comparable<K>, V> extends SortedMap<K,V>
{
private final Map<K, V> map;
private SortedMapImpl(Map<K, V> map)
{
this.map = new HashMap<K, V>(map);
}
#Override
public <C> SortedMap<K, C> map(Function<? super V, ? extends C> f)
{
// TODO Auto-generated method stub
return null;
}
#Override
public SortedMap<K, V> filter(Predicate<? super K> p)
{
final Map<K, V> filteredMap = map.entrySet()
.stream()
.filter(Predicate<? super Entry<K, V>> p)
.collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue()));
return new SortedMapImpl<K, V>(filteredMap);
}
// ...
}
As you can see I've got no clue at the moment how to implement the map() method, and the filter method is at least partly wrong. Any help is greatly appreciated!
I'll help you implement the filter, and hopefully you should get the idea and implement the map by yourself.
You need to filter the entries of the original map, and only keep the ones for which the key satisifes the key predicate:
public SortedMap<K, V> filter(Predicate<? super K> predicate) {
Map<K, V> filteredMap =
map.entrySet()
.stream()
.filter(entry -> predicate.test(entry.getKey()))
.collect(Collectors.toMap(entry -> entry.getKey(),
entry -> entry.getValue()));
return new SortedMapImpl<K, V>(filteredMap);
}
I would not use the name SortedMap, though: your map is not a map, it's not sorted either, and SortedMap is already a standard collection name, which will make your class confusing and cumbersome to use.
In Java 8, a variety of convenient utilities are provided to build efficient Spliterators from arrays. However, no factory methods are provided there to build a Spliterator with a comparator. Clearly Spliterators are allowed to have attached comparators; they have a getComparator() method and a SORTED property.
How are library authors supposed to build SORTED Spliterators?
It seems that it is not foreseen to have such a Spliterator with an order other than natural. But implementing it is not that hard. It could look like this:
class MyArraySpliterator implements Spliterator.OfInt {
final int[] intArray;
int pos;
final int end;
final Comparator<? super Integer> comp;
MyArraySpliterator(int[] array, Comparator<? super Integer> c) {
this(array, 0, array.length, c);
}
MyArraySpliterator(int[] array, int s, int e, Comparator<? super Integer> c) {
intArray=array;
pos=s;
end=e;
comp=c;
}
#Override
public OfInt trySplit() {
if(end-pos<64) return null;
int mid=(pos+end)>>>1;
return new MyArraySpliterator(intArray, pos, pos=mid, comp);
}
#Override
public boolean tryAdvance(IntConsumer action) {
Objects.requireNonNull(action);
if(pos<end) {
action.accept(intArray[pos++]);
return true;
}
return false;
}
#Override
public boolean tryAdvance(Consumer<? super Integer> action) {
Objects.requireNonNull(action);
if(pos<end) {
action.accept(intArray[pos++]);
return true;
}
return false;
}
#Override
public long estimateSize() {
return end-pos;
}
#Override
public int characteristics() {
return SIZED|SUBSIZED|SORTED|ORDERED|NONNULL;
}
#Override
public Comparator<? super Integer> getComparator() {
return comp;
}
}
But Java 8 is not entirely fixed yet. Maybe there will be a JRE-provided solution in the final.
You can create an ORDERED Spliterator:
by starting from a Collection with an appropriate iterator():
A Collection has an encounter order if the corresponding Collection.iterator() documents an order. If so, the encounter order is the same as the documented order. Otherwise, a collection does not have an encounter order.
Typically, TreeSet.spliterator#getComparator returns the TreeSet's Comparator, but ArrayList.spliterator#getComparator returns null: the order is by incrementing index.
or, if you have an array, by using the new convenience methods provided in the Arrays helper class, such as Arrays.spliterator(double[]):
The spliterator reports Spliterator.SIZED, Spliterator.SUBSIZED, Spliterator.ORDERED, and Spliterator.IMMUTABLE.
or (which is what Arrays.spliterator does) by explicitly providing characteristics, such as: Spliterators.spliterator(array, Spliterator.ORDERED);
When the collection is not associated with a particular comparator (or with arrays), it would make sense to sort before "spliterating".
I need some data structure that I can build from standard collections or using guava. So it should be mutable Map<Enum, V>. Where V is pretty interesting structure.
V requirements:
mutable
sorted by comparator (with allowing elements such as compare(a, b) == 0) - these is need for iterations
set (there is no such a and b, that a.equals(b) == true) - optional
extra optional requirement to map
keys should be iterated by their natural order
now it's HashMap<SomeEnum, LinkedList<Entity>> with different stuff like collections.sort() in the code.
Thanks.
A Sample implementation
Here is a Guava Multimap implementation of the class you need:
First the drawback: it will have to reside in package com.google.common.collect. The makers of guava have in their infinite wisdom made AbstractSortedSetMultimap package scoped.
I will use this enum in all my examples:
public enum Color{
RED, BLUE, GREEN
};
Constructing the Class
There are six constructors:
Empty (Uses a HashMap and natural ordering for values)
SortedSetMultimap<Color,String> simple =
new EnumValueSortMultiMap<Color, String>();
with a Comparator(V) (Uses a HashMap<K,SortedSet<V>> with the supplied comparator for the values)
SortedSetMultimap<Color,String> inreverse =
new EnumValueSortMultiMap<Color, String>(
Ordering.natural().reverse()
);
with a Map<K,SortedSet<V>> (use this if you want to sort keys, pass in a SortedMap implementation)
SortedSetMultimap<Color,String> withSortedKeys =
new EnumValueSortMultiMap<Color, String>(
new TreeMap<Color, Collection<String>>()
);
with a Map<K,SortedSet<V>> and a Comparator<V> (same as above, but values are sorted using custom comparator)
SortedSetMultimap<Color,String> reverseWithSortedKeys =
new EnumValueSortMultiMap<Color, String>(
new TreeMap<Color, Collection<String>>(),
Ordering.natural().reverse()
);
with a Class<K extends Enum<K>> (uses an EnumMap internally for higher efficiency, natural ordering for values)
SortedSetMultimap<Color,String> withEnumMap =
new EnumValueSortMultiMap<Color, String>(
Color.class
);
with a Class<K extends Enum<K>> and a Comparator<V> (same as above, but values are sorted using custom comparator)
SortedSetMultimap<Color,String> reverseWithEnumMap =
new EnumValueSortMultiMap<Color, String>(
Color.class, Ordering.natural().reverse()
);
Source Code
Here's the class:
package com.google.common.collect;
import java.util.Collection;
import java.util.Comparator;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;
public class EnumValueSortMultiMap<K extends Enum<K>,
V extends Comparable<? super V>>
extends AbstractSortedSetMultimap<K, V>{
private static final long serialVersionUID = 5359491222446743952L;
private Comparator<? super V> comparator;
private Class<K> enumType;
public EnumValueSortMultiMap(){
this(new HashMap<K, Collection<V>>());
}
public EnumValueSortMultiMap(final Comparator<? super V> comparator){
this(new HashMap<K, Collection<V>>(), comparator);
}
public EnumValueSortMultiMap(final Map<K, Collection<V>> map){
this(map, Ordering.natural());
}
public EnumValueSortMultiMap(final Map<K, Collection<V>> map,
final Comparator<? super V> comparator){
super(map);
this.comparator = comparator;
}
public EnumValueSortMultiMap(final Class<K> enumClass,
final Comparator<? super V> comparator){
this(new EnumMap<K, Collection<V>>(enumClass), comparator);
}
public EnumValueSortMultiMap(final Class<K> enumClass){
this(new EnumMap<K, Collection<V>>(enumClass));
}
#Override
Map<K, Collection<V>> backingMap(){
return new EnumMap<K, Collection<V>>(enumType);
}
#Override
public Comparator<? super V> valueComparator(){
return comparator;
}
#Override
SortedSet<V> createCollection(){
return new TreeSet<V>(comparator);
}
}
Other ways to do it
UPDATE: I guess the proper Guava way to do it would have been something like this (it uses the SortedArrayList class I wrote in my other answer):
public static <E extends Enum<E>, V> Multimap<E, V> getMap(
final Class<E> clz){
return Multimaps.newListMultimap(
Maps.<E, Collection<V>> newEnumMap(clz),
new Supplier<List<V>>(){
#Override
public List<V> get(){
return new SortedArrayList<V>();
}
}
);
}
If an extra class is too much, you maybe want to use the factory methods of the class Multimaps.
SortedSetMultimap<Color, Entity> set = Multimaps.newSortedSetMultimap(
new HashMap<Enum, Collection<Entity>>(),
new Supplier<TreeSet<Entity>>() {
#Override
public TreeSet<Entity> get() {
return new TreeSet<Entity>(new Comparator<Entity>() {
#Override
public int compare(Entity o1, Entity o2) {
//TODO implement
}
});
}
});
You can use an EnumMap instead of the current HashMap. EnumMaps are more efficient for enum keys. In guava check Multimap [examples].
You need an collection implementation V which is used this way: HashMap<SomeEnum, V>. The above stated requirements affect V (not Entity). Right?
I think a link TreeSet<E> should fullfill your requirents:
TreeSet implements the Set interface
Sorted by natural order or custom Comparator
Elements can be added and removed