2014-12-06 3 views
1

값이있는 문자열이 있습니다. || HelpDesk || IT 직원 || IT 직원 || 관리 || 감사 || HelpDesk ||구분 기호가있는 문자열에서 중복 값을 제거하는 방법

중복을 제거하고 다음과 같은 데미 리어를 유지하는 고유 값을 반환해야하는 코드를 작성하려고합니다. || HelpDesk || IT 직원 || 관리자 || 감사 ||

내 코드는 중복을 제거하기 위해 HashSet을 사용하지만 문제는 구분 기호를 제거한다는 것입니다. 중복 값만 제거하여 분리 문자를 유지하려면 어떻게해야합니까?

다음은 중복을 제거하고 구분 기호를 다시 추가 한 후의 코드입니다. 그러나 이것을하는 쉬운 방법이 있는지 확실하지 않습니다.

public static void main(String[] args) { 
    TestDuplicates testDuplicates = new TestDuplicates(); 
    String bRole = "||HelpDesk||IT Staff||IT Staff||Admin||Audit||HelpDesk||"; 
    List<String> listWithoutDuplicates = new ArrayList<String>(); 
    String noDup = ""; 
    List<String> splittedStringList = 
     new ArrayList<String>(); 
    SplitOperations splitOperations = 
     new SplitOperations(); 
    splittedStringList = 
      splitOperations.splitString(bRole); 
    for (int i = 0; i < splittedStringList.size(); i++) { 

     HashSet<String> listToSet = new HashSet<String>(splittedStringList); 

     listWithoutDuplicates = new ArrayList<String>(listToSet); 


    } 
    for(int i=0;i<listWithoutDuplicates.size();i++){ 
     noDup = noDup + "||"+listWithoutDuplicates.get(i); 
     System.out.println(listWithoutDuplicates.get(i)); 
    } 
    System.out.println("No Duplicate is::"+ noDup+"||"); 


} 

감사

같은
+0

분할'||'로 문자열 (당신이 필요합니다 이 문자들을 이스케이프하거나,'Pattern.quote'를 사용하여). Set의 요소에서 String을 구성 할 때 구분 기호를 다시 가져올 수 있습니다. –

+0

우리가 알기를 바랍니다. 지금까지 어떤 시도를 했습니까? – SMA

+0

HashSet에서 유일한 요소를 추출한 후에 구분 기호를 다시 추가하는 것이 좋습니다. – user314104

답변

1

LinkedHashSet을 사용하면 삽입 순서를 유지할 수 있습니다. 문자열을 "||"로 분리하면, String을 구성 할 때 단락 문자를 추가하십시오.

String s = "||HelpDesk||IT Staff||IT Staff||Admin||Audit||HelpDesk||"; 
Set<String> set = new LinkedHashSet<>(Arrays.asList(s.split(Pattern.quote("||")))); 
String noDup = "||"; 
for(String st : set) { 
    if(st.isEmpty()) continue; 
    noDup += st+"||"; 
} 

또는 새로운 자바 8 스트림 API를 사용하여 :

String noDup = "||"+ 
    Arrays.stream(s.split(Pattern.quote("||"))) 
      .distinct() 
      .filter(st -> !st.isEmpty()) //we need to remove the empty String produced by the split 
      .collect(Collectors.joining("||"))+"||"; 

는 두 가지 접근법이 같은 결과 (||HelpDesk||IT Staff||Admin||Audit||)을 얻을 수 있습니다.

0
public String removeDublicate() { 
    String str = "||HelpDesk||IT Staff||IT Staff||Admin||Audit||HelpDesk||"; 
    String split[] = str.split("\\|\\|"); 

    String newStr = ""; 

    for (String s : split) { 
     if (!s.isEmpty() && !newStr.contains(s)) { 
      newStr += "||" + s; 
     } 
    } 

    newStr += "||"; 

    return newStr; 
} 

뭔가? str이 인수가 될 수 있습니다. 당신이 && !newStr.contains(s) 제거하려면

편집 # 1

당신은 대신 HashSet<String>를 사용할 수 있습니다. 나는 그것이 과잉이라고 생각한다. .contains(s)은 문자열이 작을 때 트릭을 수행합니다.

0

원하는 경우이 순서대로 작동해야합니다. 구분 기호를 다시 입력하는 코드는 작성하지 않았습니다. 이 어딘가에 앞서 살펴 역 참조를 사용하여 앞서의 주장을 통해 자체 뒤에 모든 용어를 대체하여 작동

str = str.replaceAll("(\\|[^|]+)(?=.*\\1\\|)", ""); 

:

public static void main(String s[]){ 

     String a = "||HelpDesk||IT Staff||IT Staff||Admin||Audit||HelpDesk||"; 
     a = a.replaceAll("\\|\\|",","); 
     String arr[] = a.split(","); 
     //linked hash set in case you want to maintain the sequence of elements 
     Set<String> set = new LinkedHashSet<String>(Arrays.asList(arr)); 
     set.remove(""); 
     System.out.println(set); 
     //Iterate through the set and put your delimiters here again 
    } 
0

여기 정규식 기반의 하나 라이너입니다. 여기

Joiner.on("||").skipNulls(Splitter.on("||").trimResults().split(<target_string>);) 

이 나의 시도이다 : 그것은 한 라이너의 Guava lib를 사용

Arrays.stream(str.substring(1).split("[|]")).distinct().collect(Collectors.joining("|", "|", "|")); 
0

: 여기

가 아닌 정규식 자바 8 일 라이너의

import java.util.*; 

public class Seperator { 
    public static void main(String[] args) { 

    String bRole = "||HelpDesk||IT Staff||IT Staff||Admin||Audit||HelpDesk||"; 

    List<String> listWithoutDuplicates = new ArrayList<String>(); 

    String noDup = ""; 

    List<String> splittedStringList = new ArrayList<String>(); 

    splittedStringList = Arrays.asList(bRole.split("\\|\\|")); 

    LinkedHashSet<String> listToSet = new LinkedHashSet<String>(splittedStringList); 

    noDup = Seperator.join(listToSet, "||"); 

    System.out.println("No Duplicate is::"+ noDup+"||"); 
    } 

    public static String join(Set<String> set, String sep) { 
    String result = null; 
    if(set != null) { 
     StringBuilder sb = new StringBuilder(); 
     Iterator<String> it = set.iterator(); 
     if(it.hasNext()) { 
     sb.append(it.next()); 
     } 
     while(it.hasNext()) { 
     sb.append(sep).append(it.next()); 
     } 
     result = sb.toString(); 
    } 
    return result; 
    } 
} 

LinkedHashSet의 주로 순서를 보존하고 고유 항목을 얻는 데 사용됩니다.(소목) 가입 꽤 표준이지만, 우리는 또한 Google's Guava Library를 사용할 수 있습니다

그래서, 대신 Seperator.join(listToSet, "||");

의 당신은해야합니다 : Joiner.on("||").join(listToSet);

관련 문제