How can I make a tree with the following data:

For example, I have computer names ( y101-ws01 , y102-ws01 , y101-ws02 , y103-ws01 ). I need to make a tree, where the main directory will be у101 , and there already y101-ws01 and y101-ws01 .

    1 answer 1

    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.

    • How then can we make this data displayed in jTree, in the same hierarchy? - AlexSirk
    • @AsmaRod I don’t want to copy-paste, so keep the official tutorial from Oracle - PloadyFree
    • and one more question. Here we have y101 = [y101-ws01, y101-ws02], y102 = [y102-ws01]. How can I just add y101 to that tree? If I add rootName, then y101 is obtained twice. - AlexSirk
    • I figured out everything, for (Map.Entry<String, Set<String>> m : tree.entrySet()) { String rootName = m.getKey(); System.out.println(rootName); } for (Map.Entry<String, Set<String>> m : tree.entrySet()) { String rootName = m.getKey(); System.out.println(rootName); } for (Map.Entry<String, Set<String>> m : tree.entrySet()) { String rootName = m.getKey(); System.out.println(rootName); } - AlexSirk
    • @AsmaRod If I helped you, you can increase the rating of my answer and / or mark it as the best answer. I will be grateful. If I can help you with something else, ask, I will help. - PloadyFree