用户可以根据需要创建任意数量的Thing实例。用户将带有数字的字符串输入对象。
例如创建的对象
Thing thing1 = new Thing("input1", 3);
Thing thing2 = new Thing("input2", 1);
Thing thing3 = new Thing("input2", 3000);
Thing thing4 = new Thing("input1", 4);
Thing thing5 = new Thing("input4", 200");
ArrayList<Thing> ThingList= new ArrayList<Thing>();
ThingList.add(thing1);
.....
.....
我需要让程序在ArrayList
的事物中进行搜索,并输出输入的String以及具有相同输入字符串的所有整数的总和
输出示例
name count
input1 7
input2 3001
input4 200
我不确定如何在不加倍输入相同名称的情况下做到这一点。除非我与我输入的名字相比较
到目前为止我做了什么(请注意,它只能找到并汇总我为搜索而输入的内容。)
for( i= 0; i< ThingList.size(); i++){
inputedThingCheck = ThingList.get(i).getInputedName();
//testInput is the input I know for a fact is inside arraylist
if(inputedThingCheck.equals(testInput)){
thingTotal = ThingList.get(i).getCount() + thingTotal;
}
}
我想知道如何让程序搜索每个Thing对象并在不跳过已完成的Thing的情况下将具有相同名称的所有事物的总数加起来
答案 0 :(得分:0)
您可以使用$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'myUserName';
$db['default']['password'] = 'myPassword';
$db['default']['database'] = 'myDatabaseName';
/** Do not change the below values. Change only if you know what you are doing */
$db['default']['dbdriver'] = 'mysqli';
$db['default']['dbprefix'] = '';
$db['default']['pconnect'] = FALSE;
$db['default']['db_debug'] = TRUE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = '';
$db['default']['char_set'] = "utf8";
$db['default']['dbcollat'] = "utf8_unicode_ci";
$db['default']['swap_pre'] = '';
$db['default']['autoinit'] = TRUE;
$db['default']['stricton'] = FALSE;
$active_group = 'default';
$active_record = TRUE;
Collectors.groupingBy
谢谢!
答案 1 :(得分:0)
您还可以实现groupby函数,例如java 8
Map<String, Integer> sum = list.stream().collect(
Collectors.groupingBy(Thing::getkey, Collectors.summingInt(Thing::getValue)));
答案 2 :(得分:0)
与使用ArrayList包含事物对象不同,我想如果将其存储为键值对会更容易。键可以是事物的名称,值可以是包含该特定键的计数的数组。
ArrayList<Thing> foo = new ArrayList<Thing>();
foo.add(thing1);
foo.add(thing2);
foo.add(thing3);
foo.add(thing4);
foo.add(thing5);
Map<String, ArrayList<Integer>> ThingList = new HashMap<String, ArrayList<Integer>>();
for (Thing x : foo){
if (ThingList.containsKey(x.getName())){
ArrayList value = ThingList.get(x.getName());
value.add(x.getValue());
}
else{
container = new ArrayList<Integer>();
container.add(x.getValue());
ThingList.put(x.getName(), container);
}
}
// Debug to check the key, value pair of ThingList
// System.out.println(Arrays.asList(ThingList));
// Loop through ThingList and get the key + sum of its related values
for (Map.Entry<String, ArrayList<Integer>> entry : ThingList.entrySet()) {
String key = entry.getKey();
ArrayList value = entry.getValue();
int valueSum = 0;
for (int i=0 ; i < value.size() ; i++){
valueSum += (Integer)value.get(i);
}
// Print the output
System.out.println(key + " " + String.valueOf(valueSum));
}
}