英文:
Java GroupBy with 3 classes and Enum
问题
以下是您提供的内容的翻译部分:
我是Java的初学者。我有一个问题,似乎无法解决。
我有3个类,
public class Pet {
public String petname;
Type type;
}
public class Owner {
public String name;
public int age;
}
public class PetStore {
public Owner owner;
public ArrayList<Pet> pets;
}
我的输出目前是:
Owner Mike (39) 拥有的动物:[Cat: Sunny, Rat: Bean, Cat: Milk, Dog: Boomer]
但我想要一个不同的输出,像这样:
Owner Mike (39) 拥有的动物:[Cats: Sunny, Milk], [Rat: Bean], [Dog: Boomer]
我如何实现这个?我能使用Stream和groupBy吗?
-------------- 编辑 ---------------------
我有一个Program类,在那里我生成随机数据。我想在Petstore列表中使用groupBy。
public static List<PetStore> getAllAnimal() {
return petstore = IntStream.range(0, 20)
.mapToObj(i -> new PetStore(new Person(getOwnerName(), getOwnerAge()), new ArrayList<Pet>(getList())))
.collect(toList());
}
public static ArrayList<Pet> getList() {
int randomSize = 1 + rand.nextInt(5);
return animals = IntStream.range(0, randomSize)
.limit(randomSize)
.mapToObj(i -> new Pet(PetNameGenerator.getName(), rand()))
.collect(toCollection(ArrayList::new));
}
感谢您的帮助。
英文:
I'm a beginner in Java.I have an issue that I can't seem to solve.
I have 3 classes,
public class Pet {
public String petname;
Type type; }
public class Owner {
public String name;
public int age; }
public class PetStore {
public Owner owner;
public ArrayList<Pet> pets;}
my output is right now:
Owner Mike (39) owns the animals: [Cat: Sunny, Rat: Bean, Cat: Milk, Dog: Boomer]
But I want a different output, like this:
Owner Mike (39) owns the animals: [Cats: Sunny, Milk], [Rat: Bean], [Dog: Boomer]
How can I achieve this? Can I use Stream and groupBY?
-------------- Edit ---------------------
I have a Program Class where I generate random data. I want to user the groupBy with the Petstore List.
public static List<PetStore> getAllAnimal(){
return petstore = IntStream.range(0, 20)
.mapToObj(i -> new PetStore(new Person(getOwnerName(),getOwnerAge()), new ArrayList<Pet>(getList())))
.collect(toList());
}
public static ArrayList<Pet> getList() {
int randomSize = 1 + rand.nextInt(5);
return animals = IntStream.range(0 , randomSize)
.limit(randomSize)
.mapToObj(i -> new Pet(PetNameGenerator.getName(), rand()))
.collect(toCollection(ArrayList::new));
}
Thanks for the help.
答案1
得分: 2
按宠物类型进行分组,并使用 Collectors.mapping
提取/映射宠物实例到其名称,并将它们收集为列表。
Map<Type, List<String>> petTypeToNames = petStore.getPets()
.stream()
.collect(Collectors.groupingBy(Pet::getType,
Collectors.mapping(Pet::getPetname, Collectors.toList())));
英文:
Group by the pet's type and use Collectors.mapping
to extract/map a Pet instance to its name and collect them as a list.
Map<Type, List<String>> petTypeToNames = petStore.getPets()
.stream()
.collect(Collectors.groupingBy(Pet::getType,
Collectors.mapping(Pet::getPetname, Collectors.toList())));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论