如何使用lambda获取哈希映射中值的键数

时间:2015-12-29 15:38:24

标签: java lambda hashmap java-8 java-stream

我有一个哈希映射

var sliceArgs = Function.prototype.call.bind(Array.prototype.slice);
var toString = Function.prototype.call.bind(Object.prototype.toString);
var path = require('path');
var webpack = require('webpack');

module.exports = {
    devtool: 'source-map',
    debug: true,
    devServer: {
        historyApiFallback: true,
        contentBase: 'src/public',
        publicPath: '/__build__'
    },
    entry: {
        'app': './src/app/bootstrap',
        'vendor': './src/app/vendor.ts'
    },
    output: {
        path: root('__build__'),
        filename: '[name].js',
        sourceMapFilename: '[name].js.map',
        chunkFilename: '[id].chunk.js'
    },
    resolve: {
        extensions: ['', '.ts', '.js', '.json', '.css', '.html']
        // ,
        // alias: { jquery: 'jquery/src/jquery'}
    },
    module: {
        loaders: [
            { test: /\.json$/, loader: 'json' },
            { test: /\.css$/, loader: 'raw' },
            { test: /\.html$/, loader: 'html' },
            {
                test: /\.ts$/,
                loader: 'ts',
                exclude: [/\.spec\.ts$/, /\.e2e\.ts$/, /node_modules/]
            },
            {
                test: /\.scss$/,
                loaders: ['style', 'css?sourceMap', 'sass?sourceMap']
            },
            {
                test: /\.(woff|woff2)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
                loader: "url-loader?limit=10000&minetype=application/font-woff"
            },
            {
                test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
                loader: "file-loader"
            }
        ]
    },
    plugins: [
        new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', filename: 'vendor.bundle.js' }),
        new webpack.ProvidePlugin({ $: "jquery", jQuery: "jquery" })
    ]
};

function root(args) {
    args = sliceArgs(arguments, 0);
    return path.join.apply(path, [__dirname].concat(args));
}

function rootNode(args) {
    args = sliceArgs(arguments, 0);
    return root.apply(path, ['node_modules'].concat(args));
}

Map<Integer, List<String>> Directmap = new HashMap<Integer, List<String>>() {{ put(0, Arrays.asList(a, b)); put(1, Arrays.asList(b, c)); put(2, Arrays.asList(d)); put(3, Arrays.asList(d, e)); put(4, Arrays.asList(e)); put(5, Arrays.asList()); }};

我想计算每个值的键数。例如:Directmap: {0=[a, b], 1=[b, c], 2=[d], 3=[d, e], 4=[e], 5=[]}有一个键,"a"有两个键,...,"b"有两个键,即3和4。

我试过这样的事情:

"e"

我希望带有键数的值作为输出。像这样:

Map<Object, Long> ex = Directmap.entrySet().stream()
            .collect(Collectors.groupingBy(e -> e.getKey(), Collectors.counting()));

1 个答案:

答案 0 :(得分:7)

您可以通过平面映射地图的每个值来完成此操作。

在此代码中,仅保留地图的值(因为您对密钥不感兴趣)。每个值(List<String>)都是平面映射的,因此流管道Stream<List<String>>变为Stream<String>。最后,Stream按(groupingBy)对身份函数进行分组,对元素执行的减少只是计算出现次数(counting())。

Map<String, Long> ex = 
      Directmap.values()
               .stream()
               .flatMap(Collection::stream)
               .collect(Collectors.groupingBy(v -> v, Collectors.counting()));

请注意,如果某个值在初始地图中出现两次,则它也会计算两次。如果您想计算不同值的数量,可以在收集结果之前添加对distinct()的调用(或使用Set代替List)。