IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Collection et Stream Java Discussion :

Comment accéder aux données d'une Map contenue dans une autre Map


Sujet :

Collection et Stream Java

  1. #1
    Membre à l'essai
    Profil pro
    Étudiant
    Inscrit en
    Mai 2008
    Messages
    16
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Mai 2008
    Messages : 16
    Points : 10
    Points
    10
    Par défaut Comment accéder aux données d'une Map contenue dans une autre Map
    Bonjour,
    J'ai une Map appelée order<Cart, Client> et l'object Cart est lui-même une Map.
    J'ai lu la faq parlant de parcourrir une Map mais je n'arrive pas à acceder aux données de la Map Cart. Comment faire?

    Merci

  2. #2
    Membre émérite Avatar de Djakisback
    Profil pro
    Inscrit en
    Février 2005
    Messages
    2 021
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Février 2005
    Messages : 2 021
    Points : 2 278
    Points
    2 278
    Par défaut
    Salut,
    tes clés sont des Map ? T'es sûr qu'il n'y a pas un problème de conception pour un caddie ? En général tu stockes plutôt l'id du client en clé et le contenu en valeur.

    Sinon le principe est le même que dans ce que tu as dû voir sauf que ta boucle imbriquée doit porter sur les clés et non pas sur les valeurs.
    Vive les roues en pierre

  3. #3
    Membre à l'essai
    Profil pro
    Étudiant
    Inscrit en
    Mai 2008
    Messages
    16
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Mai 2008
    Messages : 16
    Points : 10
    Points
    10
    Par défaut
    tes clés sont des Map ? T'es sûr qu'il n'y a pas un problème de conception pour un caddie ? En général tu stockes plutôt l'id du client en clé et le contenu en valeur.
    Euh malheureusement oui, l'énoncé est de mon professeur...

    J'éessaye d'accéder au valeur de la map Cart par valeur mais je n'y arrive pas...

  4. #4
    Membre émérite Avatar de Djakisback
    Profil pro
    Inscrit en
    Février 2005
    Messages
    2 021
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Février 2005
    Messages : 2 021
    Points : 2 278
    Points
    2 278
    Par défaut
    Je pense que tu peux faire une double boucle :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
     
    for (Map.Entry<Cart, Client> i : order.entrySet()){
    for (Map.Entry<TypeCleCart, TypeValCart> j : i.getKey()){
    ...
    }
    }
    Vive les roues en pierre

  5. #5
    Membre à l'essai
    Profil pro
    Étudiant
    Inscrit en
    Mai 2008
    Messages
    16
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Mai 2008
    Messages : 16
    Points : 10
    Points
    10
    Par défaut
    Merci pour tes réponses.
    J'ai testé ce que tu as écris:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    static public String[][] getStringArrayFromOrder(Map<Cart, Client> order){
    		 //Route object Map Cart to return an array of String
    		String[][] elems = new String[order.size()][4];
    		int i = 0;
    		for(Map.Entry<Cart, Client> e : order.entrySet()){
    			for (Map.Entry<Article, Integer> j : e.getKey()){
    			i = i ++;
    			elems[i][0] = j.getKey().getDescription();
    			elems[i][1] = Double.toString(j.getKey().getPrice());
    			elems[i][2] = Integer.toString(j.getValue());			
    		}
    			elems[i][3] = e.getValue().getLogin();
    		}	
    		return elems;
    	}
    Mais pour la ligne:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    for (Map.Entry<Article, Integer> j : e.getKey()){
    il me souligne le: e.getKey()
    et m'indique ceci: Can only iterate over an array or an instance of java.lang.Iterable

  6. #6
    Membre émérite Avatar de Djakisback
    Profil pro
    Inscrit en
    Février 2005
    Messages
    2 021
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Février 2005
    Messages : 2 021
    Points : 2 278
    Points
    2 278
    Par défaut
    Légère erreur de ma part, il faut que tu types ta Map en clé et que tu parcours l'EntrySet de la clé, pas la clé :

    for(Map.Entry<Cart<Article, Integer>, Client> e : order.entrySet()){
    for (Map.Entry<Article, Integer> j : e.getKey().entrySet()){
    i = i ++;
    Vive les roues en pierre

  7. #7
    Expert éminent sénior
    Avatar de tchize_
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Avril 2007
    Messages
    25 481
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 44
    Localisation : Belgique

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Avril 2007
    Messages : 25 481
    Points : 48 806
    Points
    48 806
    Par défaut
    Pour rappel, dans une Map:

    les clés DOIVENT être immutable (au sens des méthodes equals() et hashcode()
    une Map n'est PAS immutable par défaut
    une Map ne doit JAMAIS servir de clé, ca va vous pêter à la gueule. L'implémentation doit être soit Map<Client,Cart>, soit Cart doit être rendu immutable pour que hashcode et equals ne changent pas quand on y ajoute des items.

  8. #8
    Rédacteur/Modérateur
    Avatar de Logan Mauzaize
    Homme Profil pro
    Architecte technique
    Inscrit en
    Août 2005
    Messages
    2 894
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 38
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Architecte technique
    Secteur : Transports

    Informations forums :
    Inscription : Août 2005
    Messages : 2 894
    Points : 7 083
    Points
    7 083
    Par défaut
    Citation Envoyé par leeti Voir le message
    Euh malheureusement oui, l'énoncé est de mon professeur...
    Tchize_ >
    Tu pourras rajouter celle-là à ta supplique
    Java : Cours et tutoriels - FAQ - Java SE 8 API - Programmation concurrente
    Ceylon : Installation - Concepts de base - Typage - Appels et arguments

    ECM = Exemple(reproduit le problème) Complet (code compilable) Minimal (ne postez pas votre application !)
    Une solution vous convient ? N'oubliez pas le tag
    Signature par pitipoisson

  9. #9
    Membre à l'essai
    Profil pro
    Étudiant
    Inscrit en
    Mai 2008
    Messages
    16
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Mai 2008
    Messages : 16
    Points : 10
    Points
    10
    Par défaut
    Merci beaucoup!
    C'est la première fois que je dois manipuler des Maps
    et pour mon projet, c'est un site internet dont le modèle est un JAR fait par le professeur et mon problème se situe au niveau de ma classe facade...

    => Djakisback:
    J'ai essayé comme tu m'as proposé mais il souligne en me proposant un cast... Je ne suis pas sure que ça aille

  10. #10
    Membre émérite Avatar de Djakisback
    Profil pro
    Inscrit en
    Février 2005
    Messages
    2 021
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Février 2005
    Messages : 2 021
    Points : 2 278
    Points
    2 278
    Par défaut
    Pourtant il me semblait que ce que j'avais posté fonctionnait, malgré le problème potentiel relevé par tchize

    Fais-voir ton code final et ce qui est mentionné par ton IDE.
    (Si je comprends bien ton prof te donne des classe abstraites ou interfaces à implémenter ? Après tout c'est un exercice comme un autre mais il vous a soigné là mais peut-être qu'il s'attend à ce que vous lui disiez que son jar est mauvais)

    [edit] En fait c'est ton paramètre de fonction qui devrait être :
    Map<Cart<Article, Integer>, Client> order
    Vive les roues en pierre

  11. #11
    Membre à l'essai
    Profil pro
    Étudiant
    Inscrit en
    Mai 2008
    Messages
    16
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Mai 2008
    Messages : 16
    Points : 10
    Points
    10
    Par défaut
    Voici ma classe Facade:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    package model;
     
    import java.util.List;
    import java.util.Map;
     
    public class Facade {
       private Shop shoes;
     
       public Facade(){	   
    		shoes = new Shop();
    	}
     
    	public List<Client> getClient()	{
    		return shoes.getClients();
    	}
     
    	public void addArticle(int stock, Article article){
    		this.addArticle(stock, article);
    	}
     
    	public void removeArticle(){		
    		this.removeArticle();
    	}
     
    	public void removeArticle(int stock, Article article){
    		this.removeArticle(stock, article);
    	}
     
    	public Map<Cart,Client> getOrder(){
    		Map<Cart,Client> order = this.getOrder();		
    		if(order != null)
    		{
    			return this.getOrder();
    		}
    		return null;
    	}
     
    	public double showTotalPrice(){
    		return this.showTotalPrice();
    	}
     
    	public void addOrder(Cart cart, Client client){
    		this.addOrder(cart, client);
    	}
     
    	public Stock getStock()	{
    		return shoes.getStock();
    	}
     
    }
    et voici la classe qui pose problème, que j'ai appelé Util(la méthode est getStringArrayFromOrder(Map<Cart, Client> order)):
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    package model;
     
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Map;
     
    public class Util {
     
    	static public boolean isValide(String string)
        //Determines if a string is integer
    	{
    		return (string!= null && (!string.isEmpty()));
    	}
     
    	static public String isNull(String string)
    	//Initializes a String in case the variable is null
    	{
    		if(string == null)
    		{
    			return "";
    		}
    		return string;
    	}
     
    	static public String[][] getStringArrayFrom(Map<Article, Integer> stock){
        //Fetch an object Map Stock to return an array of String
    		String[][] elems = new String[stock.size()][4];
    		int i=0;
    		for(Map.Entry<Article, Integer> e : stock.entrySet()){
    			i = i ++;
    			elems[i][0] = e.getKey().getDescription();
    			elems[i][1] = Double.toString(e.getKey().getPrice());
    			elems[i][2] = Integer.toString(e.getValue());
     
    		}
    		return elems;
    	}
     
    	static public Article findArticle(String description, Map<Article, Integer> stock){
        //Search an article in the map and returns
    		Article article;
    		for(Map.Entry<Article, Integer> e : stock.entrySet())
    		{
    			article = e.getKey();
    			if(e.getKey().getDescription().equalsIgnoreCase(description))
    			{
    				return article;
    			}
    		}
    		return null;
    	}
     
    	/*static public String[][] getStringArrayFromOrder(Map<Article, Integer> order){
       //Route object Map Cart to return an array of String
    		String[][] elems = new String[order.size()][5];
    		int i = 0;
    		for(Map.Entry<Article, Integer> e : order.entrySet()){
    			i = i ++;
    			elems[i][0] = e.getKey().getDescription();
    			elems[i][1] = Double.toString(e.getKey().getPrice());
    			elems[i][2] = Integer.toString(e.getValue());
     
    		}		
    		return elems;
    	}*/
     
    	@SuppressWarnings("unchecked")
    	static public String[][] getStringArrayFromOrder(Map<Cart, Client> order){
    		 //Route object Map to return an array of String
    		String[][] elems = new String[order.size()][4];
    		int i = 0;
    		for(Map.Entry<Cart, Client> e : order.entrySet()){
    			for (Map.Entry<Article, Integer> j : ((Map<Article, Integer>) e.getKey()).entrySet()){
    			i = i ++;
    			elems[i][0] = j.getKey().getDescription();
    			elems[i][1] = Double.toString(j.getKey().getPrice());
    			elems[i][2] = Integer.toString(j.getValue());			
    		}
    			elems[i][3] = e.getValue().getLogin();
    		}	
    		return elems;
    	}			
     
    	static public Map<Cart, Client> copyOf(Map<Cart, Client> order){
        //This method returns a copy of a Cart
    		Map<Cart, Client> copy = new HashMap<Cart, Client>();
    		copy.putAll(order);				
    		return copy;
    	}
     
    	static public boolean searchClient(List<Client> client, String login, String password) {
    		//Search if a customer exists and verifies the password
    		Iterator<Client> it = client.iterator();
    		Client clientTemp;
    		int size = client.size();
    		for(int i = 0; i < size ; i++){
    			clientTemp = it.next();
    			if(clientTemp.getLogin().equalsIgnoreCase(login)&&(clientTemp.getPwd().equalsIgnoreCase(password))){
    				return true;
    			}
    		}
    		return false;
    	}
     
    	/*public static double getTotal(Map<Cart, Client> order) {
    		//Calculating the total order
    		double total = 0;
    		int i = 0;
    		for(Entry<Cart, Client> e : order.entrySet()){
    			i = i ++;			
    			total = total + ((Article) e.getKey()).getPrice();			
    		}			
    		return 0;
    	}*/
     
    	public static double getTotalLine(int quantity, double price){
    		return quantity * price;
    	}
     
    }
    et pour la Map Cart elle est bien typée <Article, Integer>
    Merci

  12. #12
    Membre émérite Avatar de Djakisback
    Profil pro
    Inscrit en
    Février 2005
    Messages
    2 021
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Février 2005
    Messages : 2 021
    Points : 2 278
    Points
    2 278
    Par défaut
    J'ai édité mon message précédent
    En revanche, cette méthode :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    public Map<Cart,Client> getOrder(){
    		Map<Cart,Client> order = this.getOrder();		
    		if(order != null)
    		{
    			return this.getOrder();
    		}
    		return null;
    	}
    boucle à l'infini ?

    Pour le parcours dans ta méthode ça donnerait :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
     
    	static public String[][] getStringArrayFromOrder(Map<Cart<Article, Integer>, Client> order){
       //Route object Map Cart to return an array of String
    		String[][] elems = new String[order.size()][5];
    		int i = 0;
    		for(Map.Entry<Cart<Article, Integer>, Client> e : order.entrySet()){
    for (Map.Entry<Article, Integer> j : e.getKey().entrySet()){
    ...
     
    		}		
    		return elems;
    	}
    Vive les roues en pierre

  13. #13
    Expert éminent sénior
    Avatar de tchize_
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Avril 2007
    Messages
    25 481
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 44
    Localisation : Belgique

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Avril 2007
    Messages : 25 481
    Points : 48 806
    Points
    48 806
    Par défaut
    elle boucle pas, elle fait juste des trucs inutiles: si X = null, return null sinon return X, autant écrire directement return X

    Sinon:

    on incrémente i à la fin de la boucle, pas au début.

    Ensuite c'est soit i++; soit i=i+1. Parce que i=i++, i stagne à 0.

  14. #14
    Membre émérite Avatar de Djakisback
    Profil pro
    Inscrit en
    Février 2005
    Messages
    2 021
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Février 2005
    Messages : 2 021
    Points : 2 278
    Points
    2 278
    Par défaut
    Il me semble que y a appels récursifs jusqu'à plus soif

    [edit] moi aussi ^^, au début je pensais qu'elle retournait toujours null
    Vive les roues en pierre

  15. #15
    Expert éminent sénior
    Avatar de tchize_
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Avril 2007
    Messages
    25 481
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 44
    Localisation : Belgique

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Avril 2007
    Messages : 25 481
    Points : 48 806
    Points
    48 806
    Par défaut
    arf oui, en plus Je fatigue

  16. #16
    Membre à l'essai
    Profil pro
    Étudiant
    Inscrit en
    Mai 2008
    Messages
    16
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Mai 2008
    Messages : 16
    Points : 10
    Points
    10
    Par défaut
    Merci beaucoup

Discussions similaires

  1. Réponses: 8
    Dernier message: 10/07/2015, 15h14
  2. Réponses: 1
    Dernier message: 04/04/2013, 21h06
  3. Réponses: 4
    Dernier message: 24/08/2011, 18h23
  4. Réponses: 0
    Dernier message: 07/06/2009, 12h31
  5. Changer un caractère dans une chaîne contenue dans une phrase
    Par cirtey dans le forum Algorithmes et structures de données
    Réponses: 9
    Dernier message: 07/03/2007, 16h16

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo