首页 > 解决方案 > 如何为下面的java代码编写测试用例

问题描述

public class CollectionUtils {
    public static <K, V> Map<K, V> createMap(Iterable<V> values, Function<V, K> keyFunction, boolean skipNullKeys) {
        Map<K, V> map = new HashMap<>();
        for (V value : values) {
            K key = keyFunction.apply(value);
            if (key != null || !skipNullKeys) {
                map.put(key, value);
            }
        }
        return map;
    }

标签: javajunit

解决方案


我会使用小而简单的数据,例如

List<Integer> values = Arrays.asList(1, null);
Function<Integer, String> toKey = String::valueOf;
Map<String, Integer> withNull = createMap(values, toKey, false);
Map<String, Integer> noNull = createMap(values, toKey, true);

然后你可以用Map#size, Map#containsKey(需要null-key)和...get("1").equals(1).

但是正如我在评论中提到的那样,如果您的函数可能为不同的值产生相同的键,那么您只有最后一个值,例如Function<Integer, Integer> toKey = i -> i%2只会产生01作为键(和NullPointerExceptionfor -values null),因此List<Integer> values = Arrays.asList(1, 3)将产生一个Map只有一个条目"1" -> 3.


推荐阅读