【发布时间】:2020-09-26 23:16:08
【问题描述】:
我是 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) owns the animals: [Cat: Sunny, Rat: Bean, Cat: Milk, Dog: Boomer]
但我想要一个不同的输出,像这样:
Owner Mike (39) owns the animals: [Cats: Sunny, Milk], [Rat: Bean], [Dog: Boomer]
我怎样才能做到这一点?我可以使用 Stream 和 groupBY 吗?
------------- 编辑 ---------
我有一个生成随机数据的程序类。我想通过 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));
}
感谢您的帮助。
【问题讨论】:
-
你的代码是什么?
Type是什么类 -
类型是一个枚举:枚举类型 { Cat, Dog, Rat, Hamster , Fish;在我的 Program 类中,我生成了一个列表: List
petstore ,我有两种方法 -
public static List
getAllAnimal(){ return petstore = IntStream.range(0, 20) .mapToObj(i -> new PetStore(new Owner(getOwnerName(),getOwnerAge()), new ArrayList (getList()))) .collect(toList()); } 公共静态 ArrayList getList() { int randomSize = 1 + rand.nextInt(5); return 动物 = IntStream.range(0 , randomSize) .limit(randomSize) .mapToObj(i -> new Pet(PetNameGenerator.getName(), rand())) .collect(toCollection(ArrayList::new)); } -
一切都是随机创建的
-
@AlexRudenko 对不起,我做到了