我正在尝试创建一个包含对象名称(键)的哈希映射,以及包含该名称的所有对象的列表。像这样:
"bob" = obj1, obj2
"Mark" = obj3
我已经创建了一个排序方法,以便尝试完成此操作,但我无法使其工作:
public class sorter {
public static Object obj = new Object("mark");
public static Object obj1 = new Object("bob");
public static Object obj2 = new Object("mark");
public static Object obj3 = new Object("mark");
public static List<Object> objects = new ArrayList<Object>();
private static Map<String, List<Object>> map = new HashMap<String, List<Object>>();
public static List<Object> tempList = new ArrayList<Object>();
public static String key;
public static int values;
public static void sort(List<Object> objects) {
for(int i = 0; i<objects.size(); i++) {
key = objects.get(i).getName();
if(map.containsKey(key)) {
map.get(key).add(objects.get(i));
}
else {
tempList.add(objects.get(i));
map.put(key, tempList);
}
//reset
//key = null;
}
}
public static void main(String[]args) {
objects.add(obj);
//objects.add(obj1);
//objects.add(obj2);
//objects.add(obj3);
sort(objects);
System.out.println(map.get("mark"));
}
}
答案 0 :(得分:0)
目前您的代码存在多个问题。让我们来看看:
sorter
不是一个有意义的名称,并且不遵循java命名约定。 new Object("mark");
将无法编译,因为Object
类只有一个构造函数,这是默认构造函数,不带参数。objects.get(i).getName();
将无法编译,因为对象类中没有getName
方法。Object
类,在这种情况下,创建Person
类更有意义。示例:
class Person {
private String name;
// ... some additional fields
@Override
public String toString() {
return "Person1{" +
"name='" + name + '\'' +
'}';
}
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
然后你的Sorter
班级成为:
class Grouping {
public static Person obj = new Person("mark");
public static Person obj1 = new Person("bob");
public static Person obj2 = new Person("mark");
public static Person obj3 = new Person("mark");
public static List<Person> objects = new ArrayList<>();
private static Map<String, List<Person>> map = new HashMap<>();
public static void groupByName(List<Person> objects) {
map = objects.stream().collect(Collectors.groupingBy(Person::getName));
// group by the person name
}
public static void main(String[]args) {
objects.add(obj);
objects.add(obj1);
objects.add(obj2);
objects.add(obj3);
groupByName(objects);
System.out.println(map.get("mark"));
}
}
答案 1 :(得分:0)
您可以使用如下的Java8流:
container.setScrollableY(true);
container.setScrollVisible(true);