当前位置: 动力学知识库 > 问答 > 编程问答 >

java - How can i order products array by id

问题描述:

i hope you can help me i am trying to order these arrays

int pumpno[] = new int[] { 3, 4, 5, 3, 4, 6};

String desc[] = new String[] {"jam", "chesse", "milk", "water", "soup","bread"};

int cost[] = new int[] {10, 15, 23, 43, 12, 67};

I want to print in these order:

id 3

----------

desc jam

cost 10

desc water

cost 43

id 4

----------

desc chesse

cost 15

desc soup

cost 12

id 5

----------

desc milk

cost 23

id 6

----------

desc bread

cost 63

For example each array has the same lenght in this case is 9, in the firts array theare numbers with the same value for the id so, i just want to print once time the value for id and print all de values below with the same id

i just have make how to know if is equal id i make it with these

Set<String> set = new HashSet<String>();

for (int i = 0; i < pumpno.length; i++) {

if (set.contains(pumpno[i])) {

Log.d("Duplicate ", pumpno[i]);

} else {

set.add(pumpno[i]);

}

But i have no idea how to print like the example above. if you can help me thanks a lot

网友答案:

You can use HashMap which has id as key and Set<Product> as values (if you want not to have duplicates or list if you want order of products). You can fill it up in one iteration and print in another.

Product would be data structure which has description and price.

Map<int, Set<Product>> productsById = new HashMap<>();
for (int i = 0; i < pumpno.length; i++) {
    if (productsById.containsKey(pumpno[i])) {
      //add product to existing set
      productsById.get(pumpno[i]).add(new Product(desc[i], cost[i]));
    } else {
        //create set since this is first time id is shown
        Set<Product> set = new HashSet<Product>();
        set.add(new Product(desc[i], cost[i]);
        productsById.put(pumpno[i], set);
    }
}

String newLine = System.getProperty("line.separator"); 
for (int id : productsById.keySet()){
   System.out.println("id " + id + newLine);
   for (Product product : productsById.get(id)){
     System.out.println("description" + product.getDescription() + newLine);
     System.out.println("cost" + product.getCost() + newLine);   
   }
}

Hope I did not make mistakes since I typed here in markdown but that is logic.

分享给朋友:
您可能感兴趣的文章:
随机阅读: