簡體   English   中英

Java HashSet保留第一個和最后一個元素

[英]Java HashSet preserving first and last element

我正在嘗試使用Java從字符列表中刪除重復項。

例:

[a,c,b] --->字符列表1

[a,c,e,b] --->字符列表2

[a,c, ac ,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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM