You can use the Map class to solve your problem, here is an example:
import java.util.*; public class TestMain { public static void main(String[] args) { String[] names = {"y101-ws01", "y102-ws01", "y101-ws02", "y103-ws01"}; Map<String, Set<String>> tree = new HashMap<>(); for (String fullComputerName : names) { String rootName = fullComputerName.split("-")[0]; tree.computeIfAbsent(rootName, key -> new HashSet<>()) .add(fullComputerName); } tree.entrySet().forEach(System.out::println); } }
Thus, for each group (which goes to the '-' sign) we have a Set of computers that are in it. The computeIfAbsent() method will create a new set for the key (which is the name of the group) only for the first time, then will return to us either the previously existing Set or the one just created.