我有一个整数列表,可以从中计算重复次数并使用映射将其打印出来。现在,Items
列表中的每个整数都必须具有一定的值才能分配给它们。
我的输出是:
2 x 3
8 x 1
最终我想要实现的是:
2 x 3 $5.50
8 x 1 $12.50
Total = $29
这意味着整数2和8都有一个值,分别为$ 5.50和$ 12.50。
用Java在此列表中为整数分配值的最佳方法是什么?
如何处理计算?
该程序接收烘焙食品的订单-总数量以及代码作为输入。例如14个松饼。每个项目都有一套可用的软件包(例如2,5,8),每个软件包都包含成本。我使用硬币找零算法来分解可用包装中的14个松饼。
例如输入= 14个松饼
预期产量:
14松饼$ 54.8
1 x 8美元$ 24.95
3 x 2 $ 9.95
我已经使用硬币找零算法完成了封装分解,现在我正在寻找建立OO设计以实现输出的最佳方法。我对此表示感谢。
这是我的代码,用于从列表中获取重复项:
public static void packagesprint() {
List<Integer> items = Arrays.asList(8, 2, 2, 2);
Map<Integer, Long> result = items.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
for (Map.Entry<Integer,Long> entry : result.entrySet())
System.out.println(entry.getKey() + " x "+
+ entry.getValue());
}
输出:
2x3
8x1
最佳答案
有很多解决该问题的方法。我将为您介绍一些可能性。
第一种可能的方法是制作一个包含键,值和重复项数量的新对象。这是一种好方法,因为您将所有需要的数据都放在一个对象中。
请参阅下面的实现:
public class MyObject{
private int id;
private double value;
private int numberOfDuplicates;
public MyObject(){
this.id = 0;
this.value = 0;
this.numberOfDuplicates = 0;
}
public MyObject(int id, double value, int numberOfDuplicates){
this.id = id;
this.value = value;
this.numberOfDuplicates = numberOfDuplicates;
}
// INSERT GETTERS AND SETTERS BELOW
}
然后,您将以这种方式使用它:
public static void packagesprint() {
List<Integer> items = Arrays.asList(8, 2, 2, 2);
List<MyObject> myObjectList = ArrayList<>();
Map<Integer, Long> result = items.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
for (Map.Entry<Integer,Long> entry : result.entrySet()){
MyObject myObject = new MyObject();
myObject.setId(entry.getKey());
myObject.setNumberOfDuplicates(entry.getValue().intValue());
myObject.setValue(value); // <- this is where you set your value, e.g. if 2's value is 5.50, then set 5.50 as value
myObjectList.add(myObject);
}
}
另一种可能的方法是可以使用
HashMap
并将2
设置为键,将“ 5.50”设置为值。这种方法的缺点是,您仍然必须在值中搜索另一个映射(在您的情况下为result
映射)中重复项的数量。请参阅下面的实现:
public static void packagesprint() {
List<Integer> items = Arrays.asList(8, 2, 2, 2);
Map<Integer, Double> keyValuePairs = new HashMap<Integer, Double>();
Map<Integer, Long> result = items.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
for (Map.Entry<Integer,Long> entry : result.entrySet()){
keyValuePairs.put(entry.getKey(), value) // <- this is where you set your value, e.g. if 2's value is 5.50, then set 5.50 as value
}
}