有人可以帮我用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)
答案 0 :(得分:0)
这应该有效(未经测试)
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()));
答案 1 :(得分:0)
我将尽力向您解释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<Key, Value>
。
现在,一个遍历数组中所有字符串的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}
我希望这会有所帮助:)