如何在 Java 中将 int[] 转换为 Integer[]? [英] How to convert int[] to Integer[] in Java?

查看:41
本文介绍了如何在 Java 中将 int[] 转换为 Integer[]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Java 新手,很困惑.

I'm new to Java and very confused.

我有一个长度为 4 int[] 的大数据集,我想计算次数出现 4 个整数的每个特定组合.这与计算文档中的词频非常相似.

I have a large dataset of length 4 int[] and I want to count the number of times that each particular combination of 4 integers occurs. This is very similar to counting word frequencies in a document.

我想创建一个 Map 将每个 int[] 映射到列表迭代时的运行计数,但 Map 不采用原始类型.

I want to create a Map<int[], double> that maps each int[] to a running count as the list is iterated over, but Map doesn't take primitive types.

所以我做了Map

我的数据存储为 ArrayList 所以我的循环应该类似于

my data is stored as an ArrayList<int[]> so my loop should be something like

ArrayList<int[]> data = ... // load a dataset`

Map<Integer[], Double> frequencies = new HashMap<Integer[], Double>();

for(int[] q : data) {

    // **DO SOMETHING TO convert q from int[] to Integer[] so I can put it in the map

    if(frequencies.containsKey(q)) {
    frequencies.put(q, tfs.get(q) + p);
    } else {
        frequencies.put(q, p);
    }
}

我不确定在注释中需要什么代码才能将 int[] 转换为 Integer[].或者,我对正确的做法感到从根本上感到困惑.

I'm not sure what code I need at the comment to make this work to convert an int[] to an Integer[]. Or maybe I'm fundamentally confused about the right way to do this.

推荐答案

Native Java 8(一行)

使用 Java 8,int[] 可以轻松转换为 Integer[]:

int[] data = {1,2,3,4,5,6,7,8,9,10};

// To boxed array
Integer[] what = Arrays.stream( data ).boxed().toArray( Integer[]::new );
Integer[] ever = IntStream.of( data ).boxed().toArray( Integer[]::new );

// To boxed list
List<Integer> you  = Arrays.stream( data ).boxed().collect( Collectors.toList() );
List<Integer> like = IntStream.of( data ).boxed().collect( Collectors.toList() );

正如其他人所说,Integer[] 通常不是一个好的映射键.但就转换而言,我们现在有一个相对干净的原生代码.

As others stated, Integer[] is usually not a good map key. But as far as conversion goes, we now have a relatively clean and native code.

这篇关于如何在 Java 中将 int[] 转换为 Integer[]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆