Lire un fichier et extraire une Map
Bonjour à tous,
Je débute avec les Stream et j'ai quelques questions. Je souhaite lire un fichier et obtenir un objet Map en sortie.
Voici le contenu de mon fichier
Code:
1 2 3 4 5
| 1,ABC,111
2,DEF,222
3,GHI,333
4,JKL,444
5,MNO,555 |
J'ai créé l'objet à instancier lors de la lecture
Code:
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
| public class TPP {
private int id ;
private String ref ;
private String code ;
public TPP (String line) {
String[] content = line.split(",") ;
id = Integer.valueOf(content [0]) ;
ref = content[1] ;
code = content[2] ;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getRef() {
return ref;
}
public void setRef(String ref) {
this.ref = ref;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
@Override
public int hashCode() {
return (ref+code).hashCode();
}
public TPP getObject() {
return this ;
}
} |
Pour lire le fichier, fais comme ceci
Code:
1 2 3 4 5 6 7 8
| public Map<Integer, TPP> readTpp() throws Exception {
List<TPP> setTpp = Files.lines(Paths.get("D:\\tpp.txt"))
.map(ligne -> ligne.split("\\s+")).flatMap(Arrays::stream)
.map(TPP::new)
.collect(Collectors.toList());
return setTpp.stream().collect(Collectors.toMap(TPP::hashCode, TPP::getObject));
} |
ça fonctionne bien, j'ai bien ma Map.
Mais j'ai deux questions :
- est ce qu'il y a un autre moyen que de créer la méthode getObjet pour ajouter mon Objet comme valeur de la Map ?
- est ce qu'il y a moyen d'obtenir l'objet Map dès la lecture de fichier (sans passer par une liste intermédiaire)
Merci d'avance pour votre aide.