I am trying to use Java streams to create a map which contains the currency code and a string description. The code works when I try to add items 1 to 6, but when I try to add item7 (where the currencyCode param is not initialized), I get the following error.
Exception in thread "main" java.lang.NullPointerException
at java.util.concurrent.ConcurrentHashMap.putVal(ConcurrentHashMap.java:1011)
at java.util.concurrent.ConcurrentHashMap$KeySetView.add(ConcurrentHashMap.java:4595)
at Test.lambda$6(Test.java:73)
How can I modify the below code to filter out items where the currencyCode value is not initialized? I had thought that filtering out null's should do the trick, but that doesn't quite work.
public class Test {
public static void main(String[] args) {
Currency item1 = new Currency();
item1.setCurrencyCode("USD");
Currency item2 = new Currency();
item2.setCurrencyCode("GBP");
Currency item3 = new Currency();
item3.setCurrencyCode("GBP");
Currency item4 = new Currency();
item4.setCurrencyCode("AUS");
Currency item5 = new Currency();
item5.setCurrencyCode("USD");
Currency item6 = new Currency();
item6.setCurrencyCode("");
Currency item7 = new Currency();
List<Currency> list = new ArrayList<>();
list.add(item1);
list.add(item2);
list.add(item3);
list.add(item4);
list.add(item5);
list.add(item6);
list.add(item7);
Map<String, String> distinctCurrencyCodes = list.stream()
.filter( distinctByKey(p -> p.getCurrencyCode()) )
.filter(p -> (!StringUtils.equals(p.getCurrencyCode(), "USD")))
.filter(p -> p.getCurrencyCode() != "" || p.getCurrencyCode() != null)
.map(p -> p.getCurrencyCode() )
.collect( Collectors.toMap(p -> p, p -> "Blah") );
for (Map.Entry<String, String> entry : distinctCurrencyCodes.entrySet()) {
System.out.println(entry.getKey() + "/" + entry.getValue());
}
}
public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
Set<Object> seen = ConcurrentHashMap.newKeySet();
return t -> seen.add(keyExtractor.apply(t));
}
}