Forming sets from pairs of numbers I do not want to use a new data structure but the existing APIs in Java. Here's a solution. I am thinking if this can be made simpler. Input say {"1 2", "4 3", "5 5", "2 3"} and output is [1, 2, 3, 4] [5]

    static void formSet(String[] pairs) {

    List&lt;Set&lt;Integer&gt;&gt; list = new ArrayList&lt;&gt;();
    for(String s : pairs){
        String[] values = s.split(" ");
        Integer val1 = Integer.parseInt(values[0]);
        Integer val2 = Integer.parseInt(values[1]);

        Set&lt;Integer&gt; pairSet = new HashSet&lt;&gt;();
        pairSet.add(val1);
        pairSet.add(val2);

        Set&lt;Integer&gt; val1_set = null, val2_set = null;
        for(Set&lt;Integer&gt; set : list){
            if(set.contains(val1)) {
                val1_set = set;
            }

            if(set.contains(val2)) {
                val2_set = set;
            }
        }
        if(val1_set == null &amp;&amp; val2_set == null)
            list.add(pairSet);
        if(val1_set != null &amp;&amp; val2_set == null)
            val1_set.addAll(pairSet);
        if(val1_set == null &amp;&amp; val2_set != null)
            val2_set.addAll(pairSet);
        if(val1_set != null &amp;&amp; val2_set != null){
            list.remove(val2_set);
            val1_set.addAll(val2_set);
        }
    }

    for(Set&lt;Integer&gt; set : list){
        System.out.println(set);
    }
}
First and foremost : your code contains a subtle bug.
Try this input : {"1 2", "4 3", "5 5", "2 3", "1 3"}

As for style;


please respect standard naming conventions.
seperate concerns : parsing the string into a pair should be done in a separate method, this will improve readability.
it's unclear from just looking at your code what the algorithm does exactly. Try finding a better name for the method and certain variables. If that's insufficient, some documentation can also help.
probably this is an exercise, as your algorithm simply prints its result, rather than return it. But generally such methods are useless, plus it mingles concerns again. Make the method return its result, and make a client method print the result. The main method would then call three methods


&#65279;

List&lt;Set&lt;Integer&gt;&gt; pairs = parse(input);
List&lt;Set&lt;Integer&gt;&gt; clusters = calculateClusters(pairs);
print(clusters);