以前我问过这个问题,我意识到这是我的错误。该列表实际上是tag3.add。 Java how to compare 2 ArrayList of different objects
无论如何,这是故事的第二部分...... 既然我有2个列表,我如何优雅地将2个列表分开?现在好像我把列表连在了一起。对于结果,我使用它根据id本身在不同的列中进行调整:
package com.java;
import java.util.*;
public class TestList {
public static void main(String []args) {
Tag tag1 = new Tag();
tag1.setId(15);
tag1.setTag("Test");
Tag tag2 = new Tag();
tag2.setId(15);
tag2.setTag("Oracle");
Tag tag3 = new Tag();
tag3.setId(15);
tag3.setTag("OHNO CANNOE");
Tag tag4 = new Tag();
tag4.setId(16);
tag4.setTag("Test");
Tag tag5 = new Tag();
tag5.setId(16);
tag5.setTag("Oracle");
Tag tag6 = new Tag();
tag6.setId(16);
tag6.setTag("OHNO CANNOE");
List<Tag> tagList = new ArrayList<Tag>();
tagList.add(tag1);
tagList.add(tag2);
tagList.add(tag3);
tagList.add(tag4);
tagList.add(tag5);
tagList.add(tag6);
System.out.println(tagList.size());
AnotherTest test1 = new AnotherTest();
test1.setId(15);
test1.setTestcol("Another test col");
AnotherTest test2 = new AnotherTest();
test2.setId(15);
test2.setTestcol("HAHAHA");
AnotherTest test3 = new AnotherTest();
test3.setId(16);
test3.setTestcol("name it");
AnotherTest test4 = new AnotherTest();
test4.setId(16);
test4.setTestcol("checkmate");
List<AnotherTest> anotherTests = new ArrayList<AnotherTest>();
anotherTests.add(test1);
anotherTests.add(test2);
anotherTests.add(test3);
anotherTests.add(test4);
System.out.println(anotherTests.size());
List<String> getTaglist = new ArrayList<String>(tagList.size());
for(AnotherTest anotherTest : anotherTests) {
for(Tag tag: tagList) {
if(tag.getId()==anotherTest.getId()) {
//getTaglist = new ArrayList<String>();
getTaglist.add(tag.getTag());
}
}
}
for (String str: getTaglist) {
System.out.println(str);
}
/* returns:
Test
Oracle
OHNO CANNOE
Test
Oracle
OHNO CANNOE
Test
Oracle
OHNO CANNOE
Test
Oracle
OHNO CANNOE
But I want 2 separate lists.
*/
}
}
我该怎么做?
答案 0 :(得分:0)
像Map<Integer, List<String>>
这样的东西 -
Map<Integer, List<String>> tagMap = new HashMap<Integer, List<String>>();
for (AnotherTest anotherTest : anotherTests) {
int id = anotherTest.getId();
for (Tag tag : tagList) {
if (id == tag.getId()) {
List<String> al = null;
if (tagMap.containsKey(id)) { // is this `id` already populated?
al = tagMap.get(id);
} else { // No! Create a new List.
al = new ArrayList<String>();
tagMap.put(id, al);
}
// Add the tag to the List.
al.add(tag.getTag());
}
}
}