我尝试使用java从字符列表列表中删除重复项。
示例:
[a,c,b] --->字符列表1
[a,c,e,b] --->字符列表2
[a,c, a , c ,e,b] --->人物清单3
对于第一个和第二个列表,因为我们没有重复,所以需要修改它们,但 第三个列表我们确实有重复所以我需要删除重复而不触及列表的第一个和最后一个元素,以便最终结果 [a,c,e,b] 。
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
public class Execution {
public static void main(String[] args) {
execution();
}
private static <V> void execution() {
Graph<Character> graph = new Graph<>(
new Edge<>('a', 'c', 1.0),
new Edge<>('c', 'a', 1.0),
new Edge<>('b', 'c', 2.0),
new Edge<>('c', 'b', 2.0),
new Edge<>('c', 'e', 1.0),
new Edge<>('e', 'c', 1.0),
new Edge<>('b', 'e', 1.0),
new Edge<>('e', 'b', 1.0),
new Edge<>('e', 'd', 3.0),
new Edge<>('d', 'e', 3.0),
new Edge<>('d', 'b', 2.0),
new Edge<>('b', 'd', 2.0)
);
List<Path<Character>> paths = new DefaultKShortestPathFinder<Character>().findShortestPaths('a', 'b', graph, 3);
List<List<Character>> nodes = new ArrayList<List<Character>>();
List<HashSet<Character>> modified = new ArrayList<HashSet<Character>>();
for(Path<Character> path:paths) {
nodes.add(path.getNodeList());
}
for(List<Character> p:nodes) {
modified.add(new HashSet<>(p));
}
for(HashSet<Character> n:modified) {
System.out.println(n);
}
}
}
我的代码输出:
[a, b, c] [a, b, c, e] [a, b, c, e]
答案 0 :(得分:2)
我想删除重复,但是当我使用HashSet时,它会删除我的第一个和最后一个元素
HashSet
不会删除第一个或最后一个元素。 HashSet
可以防止重复并且没有排序,因此对HashSet
中的第一个或最后一个元素没有任何意义。
如果我理解了这个问题,您希望删除重复项,同时保留原始List
元素的顺序。使用LinkedHashSet
(保留广告订单):
modified.add(new LinkedHashSet<>(p));
实际上,这只会将第一个元素保留在第一个位置,所以如果原始List
的最后一个元素有多次出现,它就不会停留在最后一个位置(从那以后) List
的最后一个位置将包含已添加到Set
的字符。在创建Set
电话后,您必须将其删除并重新添加到modified.add(new LinkedHashSet<>(p))
。
for(List<Character> p:nodes) {
LinkedHashSet<Character> set = new LinkedHashSet<>(p);
set.remove(p.get(p.size()-1));
set.add(p.get(p.size()-1));
modified.add(set);
}