You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中移除List<String>的重复无序组合问题求助

Remove Reverse Duplicate Pairs from a List in Java

I have a List<String> containing pairs like ["U1,U2", "U2,U1", "U3,U2", "U2,U3", "U3,U4"]. My goal is to eliminate reverse duplicate pairs, so the expected output is ["U1,U2", "U2,U3", "U3,U4"].

I've tried the following Java code, but it doesn't correctly filter out the duplicates. Can someone help me fix this?

import java.util.*;
public class Main {
 static List<String> opList = new ArrayList<String>();
 static List<String> FinalopList = new ArrayList<String>();
 static List<String> processStrings(List<String> friends) {
 for (int i = 0; i < friends.size(); i++) {
 StringBuilder newInp = new StringBuilder();
 boolean statusOpp = false;
 boolean statusSimilar = false;
 String inp = opList.get(i);
 String[] splitFriends = inp.split(",");
 newInp.append(splitFriends[1]).append(",").append(splitFriends[0]).toString();
 System.out.println("newInp:" + newInp);
 for (int j = 0; j < friends.size(); j++) {
 if (friends.get(j).contains(newInp.toString())) {
 statusOpp = true;
 } else if (friends.get(j).contains(inp)) {
 statusSimilar = true;
 }
 }
 if (statusOpp) {
 FinalopList.add(inp.toString());
 System.out.println(inp.toString());
 } else {
 FinalopList.add(inp.toString());
 System.out.println(inp.toString());
 }
 }
 return FinalopList;
 }
 public static void main(String[] args) {
 Scanner sc = new Scanner(System.in);
 System.out.println("Enter Number of Friends Combinations separated by comma");
 int inp = sc.nextInt();
 for (int i = 0; i < inp; i++) {
 opList.add(sc.next());
 }
 processStrings(opList);
 }
}

Let's break down the issues with your current code first:

  • No actual filtering: Whether statusOpp is true or false, you're adding every input pair to the result list. This means duplicates never get removed.
  • Incorrect match check: Using contains() instead of equals() can lead to false positives (e.g., "U1,U23" would incorrectly match "U2"). You need exact matches for reversed pairs.
  • Static collection risks: Static lists retain state between method calls, which can cause unexpected behavior if you run the code multiple times.
  • Redundant loops: You're checking every pair against every other pair without tracking which pairs you've already added to the result.

Solution 1: Standardize Pairs with a Set (Efficient)

A clean, efficient approach is to "standardize" each pair by sorting its two elements. Both "U1,U2" and "U2,U1" will become the same standardized string, so we can use a Set to track which standardized pairs we've already seen and only add one instance to the result.

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter number of friend combinations:");
        int count = sc.nextInt();
        sc.nextLine(); // Consume leftover newline
        
        List<String> inputList = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            inputList.add(sc.nextLine().trim());
        }
        
        List<String> uniquePairs = getUniquePairs(inputList);
        System.out.println("Unique pairs: " + uniquePairs);
    }
    
    private static List<String> getUniquePairs(List<String> input) {
        Set<String> seenStandardizedPairs = new HashSet<>();
        List<String> result = new ArrayList<>();
        
        for (String pair : input) {
            String[] parts = pair.split(",");
            if (parts.length != 2) {
                continue; // Skip invalid pairs (adjust if needed)
            }
            
            // Sort the pair elements to create a standardized version
            String[] sortedParts = Arrays.copyOf(parts, 2);
            Arrays.sort(sortedParts);
            String standardizedPair = String.join(",", sortedParts);
            
            // Only add the original pair if we haven't seen its standardized form before
            if (!seenStandardizedPairs.contains(standardizedPair)) {
                seenStandardizedPairs.add(standardizedPair);
                result.add(pair);
            }
        }
        
        return result;
    }
}

Solution 2: Preserve First Occurrence of Pairs

If you want to keep the first occurrence of each pair (instead of the sorted standardized version), you can check if the reverse of the current pair already exists in the result list before adding it:

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter number of friend combinations:");
        int count = sc.nextInt();
        sc.nextLine(); // Consume leftover newline
        
        List<String> inputList = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            inputList.add(sc.nextLine().trim());
        }
        
        List<String> uniquePairs = getUniquePairs(inputList);
        System.out.println("Unique pairs: " + uniquePairs);
    }
    
    private static List<String> getUniquePairs(List<String> input) {
        List<String> result = new ArrayList<>();
        
        for (String pair : input) {
            String[] parts = pair.split(",");
            if (parts.length != 2) {
                continue; // Skip invalid pairs
            }
            
            // Create the reverse of the current pair
            String reversePair = parts[1] + "," + parts[0];
            
            // Only add if neither the pair nor its reverse is already in the result
            if (!result.contains(pair) && !result.contains(reversePair)) {
                result.add(pair);
            }
        }
        
        return result;
    }
}

Key Notes

  • Solution 1 runs in O(n log n) time (due to sorting each pair) and is better for large datasets. It doesn't care which version of the pair you keep, just that only one exists.
  • Solution 2 runs in O(n²) time (since List.contains() is O(n) per check) but preserves the order of first occurrence. It's fine for small lists.

内容的提问来源于stack exchange,提问作者Maria

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 14:57:28