【问题标题】:How to write this Python code to remove duplicate values Java?如何编写此 Python 代码以删除重复值 Java?
【发布时间】:2019-07-18 10:06:45
【问题描述】:

有人可以帮我用 Java 编写这段代码吗?我还是个初学者,在 Lynda.com 上看到了一门关于算法的课程。但是,该课程是基于python的。非常感谢任何帮助。

# using a hashtable to count individual items

# define a set of items that we want to count
items = ["apple", "pear", "orange", "banana", "apple",
         "orange", "apple", "pear", "banana", "orange",
         "apple", "kiwi", "pear", "apple", "orange"]

# create a hashtable object to hold the items and counts
counter = dict()

# iterate over each item and increment the count for each one
for item in items:
    if item in counter.keys():
        counter[item] += 1
    else:
        counter[item] = 1

# print the results
print(counter)

【问题讨论】:

  • 你试过自己翻译成Java吗?
  • 这不是代码转换网站。但这些可能会有所帮助:itemsListcounterMap,我希望您已经了解 forif elseprint 语句。

标签: python hashmap


【解决方案1】:

我会尽量简单的给你解释一下java代码,并把它从1转换成1:

String[] fruits = {"apple", "pear", "orange", "banana", "apple",
         "orange", "apple", "pear", "banana", "orange",
         "apple", "kiwi", "pear", "apple", "orange"};

这只是水果数组。 String代表数据类型,[]定义了它的一个数组。

HashMap<String,Integer> counter = new HashMap<String,Integer>();

HashMap 是一种映射数据类型,类似于 python 中的dict。在 括号中,两种数据类型定义为HashMap&lt;Key, Value&gt;

现在,对数组中的所有字符串进行 foreach 循环:

for(String fruit: fruits){
    if(!counter.containsKey(fruit)) //If counter map does not contain the fruit yet
        counter.put(fruit, 1); //add it
    else 
        counter.put(fruit,counter.get(fruit) + 1); // else count one up
}

现在只需打印输出:

System.out.println(counter); //{orange=4, banana=2, apple=5, pear=3, kiwi=1}

我希望这会有所帮助:)

【讨论】:

    【解决方案2】:

    这应该可以工作(未经测试)

    List<String> items = Arrays.asList("apple", "pear", "orange", "banana", "apple", "orange", "apple", "pear", "banana", "orange", "apple",
        "kiwi", "pear", "apple", "orange");
    
    // solution 1
    HashMap<String, Integer> itemToCountMap1 = new HashMap<>();
    for (String item : items) {
      Integer currentValue = itemToCountMap1.get(item);
      if (currentValue == null) { // currently not in the map
        itemToCountMap1.put(item, 1);
      } else { //was already in the map
        itemToCountMap1.put(item, currentValue + 1);
      }
    }
    
    // solution 2
    Map<String, Long> itemToCountMap2 = items.stream().collect(Collectors.groupingBy(s -> s, Collectors.counting()));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多