我有两个ArrayLists
ArrayList<String> firstList = new ArrayList<>(Arrays.asList("king", "king", "queen", "jack", "queen"));
ArrayList<String> secondList = new ArrayList<>(Arrays.asList("one", "one", "one", "two", "one"));
在名为firstList
的列表中,我将使用Set<String> hashSet = new HashSet<>(firstList);
删除重复项,输出将为"king", "queen", "jack"
我想做的是使secondList
上的位置等于firstList
上的位置。
当前输出为(king & one), (queen, one), (jack, one)
我希望输出是(king, one), (queen, one), (jack, two)
如果有谁能帮助我,我将非常感谢。
答案 0 :(得分:2)
假设两个输入列表的长度始终相同,则可以执行以下简单操作:
public static void main(String[] args) {
List<String> firstList = new ArrayList<>(Arrays.asList("king", "king", "queen", "jack", "queen"));
List<String> secondList = new ArrayList<>(Arrays.asList("one", "one", "one", "two", "one"));
List<String> cards = new ArrayList<>();
List<String> positions = new ArrayList<>();
for(int i = 0; i< firstList.size(); i++){
String temp = firstList.get(i);
if(!cards.contains(temp)){
cards.add(temp);
positions.add(secondList.get(i));
}
}
System.out.println(cards);
System.out.println(positions);
}
答案 1 :(得分:1)
使用Map
。在Java 8中,它将是(以通过单元测试的形式):
final List<String> one = asList("king", "king", "queen", "jack", "queen");
final List<String> two = asList("one", "one", "one", "two", "one");
//Guards against IndexOutOfBoundsExceptions
final int size = Math.min(one.size(), two.size());
//LinkedHashMap to preserve key ordering
final Map<String,String> map = new LinkedHashMap<>(size);
for(int i = 0; i < size; i++) {
map.putIfAbsent(one.get(i), two.get(i));
}
final String actual = map.entrySet().stream()
.map(e -> String.format("[%s,%s]", e.getKey(), e.getValue()))
.collect(Collectors.joining(","));
final String expected = "[king,one],[queen,one],[jack,two]";
assertEquals(expected, actual);
对于Java 7,您需要在添加密钥之前检查Map
是否包含密钥。 putIfAbsent()
会为您执行此操作。
如果您想对它们进行不同的操作,则可以在之后流化Map
值和键:
final String keys = String.join(",", map.keySet());
assertEquals("king,queen,jack", keys);
final String values = String.join(",", map.values());
assertEquals("one,one,two", values);