I ont la classe Personneet options de recherche interne Carte java
private String name;
private int age;
private Map<String, LocalDate> carsBoughWithDate;
Vous pouvez ignorer le nom et l'âge. L'importante ici est carsBoughWithDate
pour une raison quelconque je sauve les voitures personne bough dans une carte avec la date
données de test
Map<String, LocalDate> carsbought = new HashMap<>();
carsbought.put("Toyota", LocalDate.of(2017, 2, 1));
carsbought.put("Corolla", LocalDate.of(2017, 2, 1));
Person john = new Person("John", 22, carsbought);
carsbought = new HashMap<>();
carsbought.put("Vauxhall", LocalDate.of(2017, 1, 1));
carsbought.put("BMW", LocalDate.of(2017, 1, 1));
carsbought.put("Toyota", LocalDate.of(2017, 1, 1));
Person michael = new Person("Michael", 44, carsbought);
List<Person> personList = new ArrayList<>();
personList.add(john);
personList.add(michael);
Sortie:
[Person{name='John', age=22, carsBoughWithDate={Toyota=2017-02-01, Corolla=2017-02-01}},
Person{name='Michael', age=44, carsBoughWithDate={Vauxhall=2017-01-01, Toyota=2017-01-01, BMW=2017-01-01}}]
Maintenant, je dois trouver la personne qui a acheté des voitures, mais ensuite trier la personne qui a acheté la voiture le plus tôt dans la liste.
Exemple: recherche personne qui a des voitures "Toyota" ou BMW
C'est ce que je l'ai fait
**
System.out.println("Before sort >" + personList);
List<Person> sortedList = Lists.newArrayList();
HashMap<LocalDate, Person> collect = Maps.newHashMap();
for (Person person : personList) {
Map<String, LocalDate> docCarsBoughWithDate = person.getCarsBoughWithDate();
collect.putAll(docCarsBoughWithDate.entrySet().stream()
.filter(map -> Lists.newArrayList("Toyota", "BMW").contains(map.getKey()))
.collect(HashMap::new,
(m, v) -> m.put(
v.getValue(),
person),
HashMap::putAll
));
}
Map<String, List<Person>> collect1 = collect.entrySet().stream().sorted(Map.Entry.comparingByKey()).map(m -> m.getValue()).collect(Collectors.groupingBy(Person::getName));
collect1.keySet().forEach(key -> sortedList.add(collect1.get(key).get(0)));
System.out.println("after sort > " + sortedList
);
Tout cela fonctionne
Avant sort>
[Person{name='John', age=22, carsBoughWithDate={Toyota=2017-02-01, Corolla=2017-02-01}}, Person{name='Michael', age=44, carsBoughWithDate={Vauxhall=2017-01-01, Toyota=2017-01-01, BMW=2017-01-01}}]
après tri>
[Person{name='Michael', age=44, carsBoughWithDate={Vauxhall=2017-01-01, Toyota=2017-01-01, BMW=2017-01-01}}, Person{name='John', age=22, carsBoughWithDate={Toyota=2017-02-01, Corolla=2017-02-01}}]
Je pense que c'est peu encombrant. Puis-je simplifier la logique?
Merci. C'est la manière la plus simple de l'écrire. J'aime l'utilisation de Flatmap et de la simpletry :) – Makky