[英]Java HashSet preserving first and last element
我正在尝试使用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]
我想删除重复项,但是当我使用HashSet时,它删除了我的第一个和最后一个元素
HashSet
不会删除第一个或最后一个元素。 HashSet
防止重复并且没有排序,因此HashSet
的第一个或最后一个元素没有意义。
如果我理解这个问题,那么您想删除重复项,同时保留原始List
的元素顺序。 使用LinkedHashSet
(保留插入顺序):
modified.add(new LinkedHashSet<>(p));
实际上,这只会将第一个元素保持在第一个位置,因此,如果原始List
的最后一个元素多次出现,它将不会停留在最后一个位置(因为List
的最后一个位置将包含一个字符已添加到Set
)。 创建modified.add(new LinkedHashSet<>(p))
调用后,您必须删除它并将其重新添加到Set
。
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.