map< >在map中< >作为值->如何从map创建对象< >其中值是另一个map< >?

chhkpiq4  于 2021-07-03  发布在  Java
关注(0)|答案(2)|浏览(418)

这里的任务是练习Map和收藏。
我们有两个类,其属性在括号中
第一类:客户机(字符串名称、字符串姓氏、整数年龄、bigdecimal现金)
下面是主目录中随机客户端的列表

List<Client> clients = List.of(
            new Client("Ola", "Chrzaszcz", 34, new BigDecimal("200")),
            new Client("Ala", "Kowalsky", 24, new BigDecimal("4000")),
            new Client("Olaf", "Chrzaszcz", 19, new BigDecimal("3999")),
            new Client("Piotr", "Nowak", 21, new BigDecimal("2099")),
            new Client("Ola", "Szwed", 45, new BigDecimal("3000"))
);

第二类:产品(字符串名称、枚举类别、bigdecimal价格)

List<Product> products = List.of(
            new Product("Szynka", Category.A, new BigDecimal(29)),
            new Product("Ser", Category.B, new BigDecimal(22)),
            new Product("Chleb", Category.C, new BigDecimal(6)),
            new Product("Maslo", Category.D, new BigDecimal(4)),
            new Product("Kielbasa", Category.A, new BigDecimal(25)),
            new Product("Jajka", Category.A, new BigDecimal(8)),
            new Product("Szynka", Category.C, new BigDecimal(25))
);

目标->预期结果:在类main中创建shopping类的示例,其中属性是带有<key:client,value:map<product,integer>的map,并用随机数据填充它//integer-购买了多少产品
问题:
如何用这样的装潢打造购物班
如何在main中用随机数据创建这个shopping类的示例?
我所做的->当前行为:
创建的独立类购物:
代码

public class Shopping {

    private Map<Client, Map<Product,Integer>> quantitiesOfProductsBoughtByClient;

main中从shopping class->创建随机对象的代码正在尝试diff组合,但仍然失败
代码

Map<Client, Map<Product,Integer>> s1 = new HashMap<>();
s1.put(clients.indexOf(0), new Map(products.indexOf(1),5) );

List<Shopping> productsBoughtByClient = List.of(
      new Map<Client, Map<Product,Integer>>(clients.indexOf(0), new Map<>(products.indexOf(0),5) ),
        );

顺便说一句,我试图找到类似的问题,但没有找到任何,

alen0pnh

alen0pnh1#

这里有一个例子作为起点,这里有一个方法 randomProductMap 它接受一个产品列表,shuffel这个列表,取一个随机数的产品并生成一个随机数的产品图。注意:我使用lombok来保存一些代码行,如果不需要的话就删除它。

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.function.Function;
import java.util.stream.Collectors;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

public class Test {

    public static void main(String[] args) {
        List<Client> clients = List.of(
                new Client("Ola", "Chrzaszcz", 34, new BigDecimal("200")),
                new Client("Ala", "Kowalsky", 24, new BigDecimal("4000")),
                new Client("Olaf", "Chrzaszcz", 19, new BigDecimal("3999")),
                new Client("Piotr", "Nowak", 21, new BigDecimal("2099")),
                new Client("Ola", "Szwed", 45, new BigDecimal("3000"))
        );
        List<Product> products = List.of(
                new Product("Szynka", Category.A, new BigDecimal(29)),
                new Product("Ser", Category.B, new BigDecimal(22)),
                new Product("Chleb", Category.C, new BigDecimal(6)),
                new Product("Maslo", Category.D, new BigDecimal(4)),
                new Product("Kielbasa", Category.A, new BigDecimal(25)),
                new Product("Jajka", Category.A, new BigDecimal(8)),
                new Product("Szynka", Category.C, new BigDecimal(25))
        );
        Map<Client,Map<Product,Integer>> myMap = 
                clients.stream().collect(Collectors.toMap(
                        Function.identity(), c -> randomProductMap(products)));

        Shopping sh = new Shopping(myMap);

        sh.getQuantitiesOfProductsBoughtByClient()
                .forEach((client, prodMap) -> {
                    System.out.println(client.getName() + " " + client.getLastName() + " bought below products");
                    prodMap.forEach((key,value) -> {
                        System.out.println("\t" + value + " x " + key.getName());
                    });
                    //Edited
                    BigDecimal total = prodMap.entrySet().stream()
                        .map(e -> e.getKey().getPrice().multiply(BigDecimal.valueOf(e.getValue())))
                        .reduce(BigDecimal.ZERO, (p,q)-> p.add(q), BigDecimal::add);
                    System.out.println("and spent total amount of: " + total);
                    //Edited
                });
    }

    public static Map<Product,Integer> randomProductMap(List<Product> products){
        List<Product> copy = new ArrayList<>(products);
        Collections.shuffle(copy);
        Random r = new Random();
        List<Product> randomSizeList = copy.subList(0, r.nextInt(products.size()) + 1);
        return randomSizeList.stream()
                .collect(Collectors.toMap(Function.identity(), p -> r.nextInt(10)+1));
    }

    @Getter
    @Setter
    @AllArgsConstructor
    @ToString
    public static class Client {
        String name;
        String lastName;
        Integer age;
        BigDecimal cash;
    }

    @Getter
    @Setter
    @AllArgsConstructor
    @ToString
    public static class Product {
        String name;
        Enum category;
        BigDecimal Price;
    }

    public static enum Category {
        A, B, C, D;
    }

    @Getter
    @Setter
    @AllArgsConstructor
    @ToString
    public static class Shopping{
        private Map<Client, Map<Product,Integer>> quantitiesOfProductsBoughtByClient;

    }
}

编辑

public Client clientWithMostExpShoping() {
    return quantitiesOfProductsBoughtByClient.entrySet()
             .stream()
             .collect(Collectors.toMap(
                     Map.Entry::getKey,  
                     entry -> entry.getValue().entrySet().stream()
                             .map(prodMap -> prodMap.getKey().getPrice().multiply(BigDecimal.valueOf(prodMap.getValue())))
                             .reduce(BigDecimal.ZERO, (prod1,prod2)-> prod1.add(prod2), BigDecimal::add)
             )).entrySet().stream()
             .max(Comparator.comparing(Map.Entry::getValue))
             .get().getKey();                            
 }

上面的方法应该给你的客户谁花费最多。这里发生了什么:遍历Map quantitiesOfProductsBoughtByClient collect以客户为键Map,并将每个产品的价格与数量和总和相乘,最后通过使用 Stream.max .
虽然上述将返回一个客户要求,你不会得到额外的信息,例如他到底花了多少钱。因此,我建议您将方法的返回值更改为 Map.Entry<Client, BigDecimal> 得到客户和总消费。为了这个,把最后一个撇开 .getKey(); ```
...
.max(Comparator.comparing(Map.Entry::getValue))
.get();

或者更简单,只需返回map<client,bigdecimal>client to total spending map,并将客户机的确定值与high、lowest、average或其他值留给方法的调用者:

public Map<Client, BigDecimal> totalSpendingsByClient() {
return quantitiesOfProductsBoughtByClient.entrySet()
.stream()
.collect(Collectors.toMap(
Map.Entry::getKey,
entry -> entry.getValue().entrySet().stream()
.map(prodMap -> prodMap.getKey().getPrice().multiply(BigDecimal.valueOf(prodMap.getValue())))
.reduce(BigDecimal.ZERO, (prod1,prod2)-> prod1.add(prod2), BigDecimal::add)
));
}

然后您可以使用获取具有最大或最小开销的客户机,例如:

Map<Client, BigDecimal> clientsTotal = totalSpendingsByClient();
Client cliWithMaxTotal = clientsTotal.entrySet().stream().max(Comparator.comparing(Map.Entry::getValue)).get().getKey();
Client cliWithMinTotal = //the same as above just change max to min

eoigrqb6

eoigrqb62#

已解决,非常感谢帮助//s1-新建Map
map<client,map<product,integer>>customerswiththeirshopping=newhashmap<>();
//向Map添加值
customerswiththeirshopping.put(clients.get(0),map.of(products.get(0),new integer(5));
customerswiththeirshopping.put(clients.get(1),map.of(products.get(1),6));

相关问题