Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/312.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何根据顺序计算列表中的重复值_Java_List_Duplicates - Fatal编程技术网

Java 如何根据顺序计算列表中的重复值

Java 如何根据顺序计算列表中的重复值,java,list,duplicates,Java,List,Duplicates,我在计算列表中的重复值时遇到问题。 我有这个列表[1 2 7 2 3 4 4 5],我想根据它们的顺序计算其中的重复值,并得到这个输出 [0 0 1 0 1 0] 另一个例子:[4 5 2 2 7 9 9]->[0 0 0 1 2 0 1 2] 有人帮我用java实现吗? 我已经尝试过使用集合。频率(list,list.get(i))但它对我没有帮助。我相信您希望计算一个数字在该列表中出现的次数。为此,您必须创建一个hashmap。然后迭代列表并将数字存储到hashmap中,同时计算它出现的次数

我在计算列表中的重复值时遇到问题。 我有这个列表[1 2 7 2 3 4 4 5],我想根据它们的顺序计算其中的重复值,并得到这个输出 [0 0 1 0 1 0]

另一个例子:[4 5 2 2 7 9 9]->[0 0 0 1 2 0 1 2]

有人帮我用java实现吗?
我已经尝试过使用集合。频率(list,list.get(i))但它对我没有帮助。

我相信您希望计算一个数字在该列表中出现的次数。为此,您必须创建一个hashmap。然后迭代列表并将数字存储到hashmap中,同时计算它出现的次数。您必须将数字存储为键,并将其显示的次数存储为其值

我相信您希望计算一个数字出现在该列表中的次数。为此,您必须创建一个hashmap。然后迭代列表并将数字存储到hashmap中,同时计算它出现的次数。您必须将数字存储为键,并将其显示的次数存储为其值

这里有一个适合您的Java 7解决方案。它重用输入
列表
,以存储频率。Java8中可能有一个2-3线性解决方案

List<Integer> input = Arrays.asList(1, 2, 7, 2, 3, 3, 4, 4, 5);
Map<Integer, Integer> counts = new HashMap<Integer, Integer>();

for (int i=0; i < input.size(); ++i) {
    int val = input.get(i);
    Integer count = (counts.get(val) == null) ? 0 : counts.get(val) + 1;
    input.set(i, count);
    counts.put(val, count);
}

System.out.println(input);
我还使用您的另一个示例对代码进行了测试,结果表明:

[4 5 2 2 2 7 9 9 9] -> [0 0 0 1 2 0 0 1 2]

下面是一个Java7解决方案,它应该适合您。它重用输入
列表
,以存储频率。Java8中可能有一个2-3线性解决方案

List<Integer> input = Arrays.asList(1, 2, 7, 2, 3, 3, 4, 4, 5);
Map<Integer, Integer> counts = new HashMap<Integer, Integer>();

for (int i=0; i < input.size(); ++i) {
    int val = input.get(i);
    Integer count = (counts.get(val) == null) ? 0 : counts.get(val) + 1;
    input.set(i, count);
    counts.put(val, count);
}

System.out.println(input);
我还使用您的另一个示例对代码进行了测试,结果表明:

[4 5 2 2 2 7 9 9 9] -> [0 0 0 1 2 0 0 1 2]

以下是Python中的解决方案: (
a
是您的列表)

演示:

>>> a = [1, 2, 7, 2, 3, 3, 4, 4, 5]
>>> print map(lambda x:sum([1 for i in a[:x[0]] if i==x[1]]) , enumerate(a))
[0, 0, 0, 1, 0, 1, 0, 1, 0]

以下是Python中的解决方案: (
a
是您的列表)

演示:

>>> a = [1, 2, 7, 2, 3, 3, 4, 4, 5]
>>> print map(lambda x:sum([1 for i in a[:x[0]] if i==x[1]]) , enumerate(a))
[0, 0, 0, 1, 0, 1, 0, 1, 0]

最初是一般问题,后来OP添加了条件。最初是一般问题,后来OP添加了条件。非常感谢。非常有帮助的回答。非常感谢。非常有用的答案。