简体   繁体   中英

Java stream and filtering to a Map producing an error

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));
    }
}

Problem is in distinctByKey() method actually.

When you are sending a null to add in Set then exception happening. Just change your distinctByKey() method to this. I handled null in this method.

public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
    Set<Object> seen = ConcurrentHashMap.newKeySet();
    return t -> {
        Object currencyName = keyExtractor.apply(t);
        if(currencyName == null)
            return false;
        return seen.add(currencyName);
    };
}

If you do like this you do not need to add this filter any more:

.filter(p -> p.getCurrencyCode() != "" && p.getCurrencyCode() != null)

You can remove this. So your filtered portion will be:

Map<String, String> distinctCurrencyCodes = list.stream()
            .filter(distinctByKey(p -> p.getCurrencyCode()))
            .filter(p -> (!StringUtils.equals(p.getCurrencyCode(), "USD")))
            .map(p -> p.getCurrencyCode() )
            .collect( Collectors.toMap(p -> p, p -> "Blah") );

Your filter to avoid null is wrong, should be &&.

The 7th currency with null value is going through (because null != "") and breaking because null can't be a key on a map.

Try

.filter(p -> p.getCurrencyCode() != "" && p.getCurrencyCode() != null)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM