Display ArrayList data in tree structure in java - java

I have an arrayList with following values:
static ArrayList<DTONodeDetail> tree;
public static void main(String[] args) {
// TODO Auto-generated method stub
tree=new ArrayList<DTONodeDetail>();
//first argument->NodeId
//second->NodeName
// third -> ParentNodeId
tree.add(getDTO(1,"Root",0));
tree.add(getDTO(239,"Node-1",1));
tree.add(getDTO(242,"Node-2",239));
tree.add(getDTO(243,"Node-3",239));
tree.add(getDTO(244,"Node-4",242));
tree.add(getDTO(245,"Node-5",243));
displayTree(tree.get(0));
}
public static DTONodeDetail getDTO(int nodeId,String nodeName,int parentID)
{
DTONodeDetail dto=new DTONodeDetail();
dto.setNodeId(nodeId);
dto.setNodeDisplayName(nodeName);
dto.setParentID(parentID);
return dto;
}
Now i want to display above data in tree structure as below using simple java code:
Root
-----Node-1
------------Node-2
------------------Node-4
------------Node-3
------------------Node-5
I have tried following but unable to get desire result:
public static void displayTree(DTONodeDetail dto){
ArrayList<DTONodeDetail> childs = selectChild(dto.getNodeId());
System.out.println(dto.getNodeDisplayName());
for(DTONodeDetail obj:childs){
displayTree(obj);
}
}
public static ArrayList<DTOWorkSpaceNodeDetail> selectChild(int nodeID){
ArrayList<DTOWorkSpaceNodeDetail> list=new ArrayList<DTOWorkSpaceNodeDetail>();
for(int i=0;i<tree.size();i++)
{
if(tree.get(i).getParentID()==nodeID){
list.add(tree.get(i));
}
}
return list;
}
Please Provide some guide or code.

You should do like this
static void displayTree(DTONodeDetail root ,int level){
System.out.print(prefix(level));
System.out.println(root.name);
ArrayList<DTONodeDetail> children = selectChild(dto.getNodeId());
for(DTONodeDetail child : children){
displayTree(child, level + 1);
}
}
the prefix is a func to build enough '----'
static String prefix(int level){
StringBuilder s = new StringBuilder();
for(int i = 0; i < level; i++){
s.append("----");
}
return s.toString();
}
Result
displayTree(node1, 0);
Node-1
----Node-2
--------Node-4
----Node-3
--------Node-5

The only problem with your implementation that I see, is that the output is as expected, but flat (i.e. no ---- at the beginning of child lines). This is because displayTree() currently has no way of knowing at which level the node it is printing is.
I propose this:
public static void displayTree(DTONodeDetail dto, int charsBeforeNodename){
ArrayList<DTONodeDetail> childs = selectChild(dto.getNodeId());
for(int i = 0; i <= charsBeforeNodename; i++){
System.out.println("-");
}
System.out.println(dto.getNodeDisplayName());
for(DTONodeDetail obj:childs){
displayTree(obj, charsBeforeNodename + dto.getNodeDisplayName().length());
}
}

Sorry, I misunderstood the question.
I updated them.
public class DTONodeDetail {
private int nodeId;
private String nodeName;
private int parentId;
public DTONodeDetail() {
}
public DTONodeDetail(int nodeId, String nodeName, int parentId) {
this.nodeId = nodeId;
this.nodeName = nodeName;
this.parentId = parentId;
}
public int getNodeId() {
return nodeId;
}
public void setNodeId(int nodeId) {
this.nodeId = nodeId;
}
public String getNodeName() {
return nodeName;
}
public void setNodeName(String nodeName) {
this.nodeName = nodeName;
}
public int getParentId() {
return parentId;
}
public void setParentId(int parentId) {
this.parentId = parentId;
}
private static List<DTONodeDetail> tree;
public static DTONodeDetail getDTO(int nodeId, String nodeName, int parentID) {
DTONodeDetail dto = new DTONodeDetail();
dto.setNodeId(nodeId);
dto.setNodeName(nodeName);
dto.setParentId(parentID);
return dto;
}
private static List<DTONodeDetail> selectChildren(int parentId) {
List<DTONodeDetail> result = new ArrayList<DTONodeDetail>();
for (DTONodeDetail d : tree) {
if (d.getParentId() == parentId) {
result.add(d);
}
}
return result;
}
public static void displayTree(DTONodeDetail dto, int level) {
List<DTONodeDetail> childs = selectChildren(dto.getNodeId());
String space = "";
for (int i = 0; i < level; i++) {
space += "\t";
}
System.out.println(space + dto.getNodeName());
if(childs.size()>0){
level ++;
}
for (DTONodeDetail obj : childs) {
displayTree(obj, level);
}
}
public static void main(String[] args) {
tree = new ArrayList<DTONodeDetail>();
tree.add(getDTO(1, "Root", 0));
tree.add(getDTO(239, "Node_1", 1));
tree.add(getDTO(242, "Node_2", 239));
tree.add(getDTO(243, "Node_3", 239));
tree.add(getDTO(244, "Node_4", 242));
tree.add(getDTO(245, "Node_5", 243));
displayTree(tree.get(0), 0);
}
}
Result:
Root
Node_1
Node_2
Node_4
Node_3
Node_5

Related

How to create a Java object of my type from a predefined set of classes?

I need a hint as to how to solve this problem I have, so I can make a start on this.
I have these 3 classes (cannot be changed or modified):
GraphDescriptor
NodeDescriptor
LinkDescriptor
GraphDescriptor:
public class GraphDescriptor {
public Set<NodeDescriptor> nodes;
public GraphDescriptor() {
nodes = new HashSet<NodeDescriptor>();
}
public Set<NodeDescriptor> getNodes() {
return nodes;
}
public void setNodes(Set<NodeDescriptor> nodes) {
this.nodes = nodes;
}
}
NodeDescriptor:
public class NodeDescriptor {
private Set<LinkDescriptor> links;
public NodeDescriptor() {
links = new HashSet<LinkDescriptor>();
}
public Set<LinkDescriptor> getLinks() {
return links;
}
public void setLinks(Set<LinkDescriptor> links) {
this.links = links;
}
}
LinkDescriptor:
public class LinkDescriptor {
private NodeDescriptor sourceNode; //a Descriptor for the source node of the link
private NodeDescriptor destinationNode; // a Descriptor for the destination node of the link
public LinkDescriptor() {
}
public NodeDescriptor getSourceNode() {
return sourceNode;
}
public void setSourceNode(NodeDescriptor sourceNode) {
this.sourceNode = sourceNode;
}
public NodeDescriptor getDestinationNode() {
return destinationNode;
}
public void setDestinationNode(NodeDescriptor destinationNode) {
this.destinationNode = destinationNode;
}
}
And I have MY classes myGraph, Nodes, Links, Node and Link :
myGraph:
public class MyGraph {
protected Nodes nodes;
protected Links links;
protected String name;
public Nodes getNodes() {
return nodes;
}
public void setNodes(Nodes value) {
this.nodes = value;
}
public Links getLinks() {
return links;
}
public void setLinks(Links value) {
this.links = value;
}
public String getName() {
return name;
}
public void setName(String value) {
this.name = value;
}
}
Nodes:
public class Nodes {
protected List<Nodes.Node> node;
public List<Nodes.Node> getNode() {
if (node == null) {
node = new ArrayList<Nodes.Node>();
}
return this.node;
}
Node:
public static class Node {
protected String name;
public String getName() {
return name;
}
public void setName(String value) {
this.name = value;
}
}
Links:
public class Links {
protected List<Links.Link> link;
public List<Links.Link> getLink() {
if (link == null) {
link = new ArrayList<Links.Link>();
}
return this.link;
}
}
Link
public static class Link {
protected String name;
protected String source;
protected String destination;
public String getName() {
return name;
}
public void setName(String value) {
this.name = value;
}
public String getSource() {
return source;
}
public void setSource(String value) {
this.source = value;
}
public String getDestination() {
return destination;
}
public void setDestination(String value) {
this.destination = value;
}
}
I need to create a new graph object of my type (myGraph) given a an instance of GraphDescriptor.
The problem I have is since the descriptors (node or link) don't have a name, I can't find a way to interconnect them.
For example: First, I can start by creating a MyGraph graph, then I can create a new Node for each NodeDescriptor belonging to the set of GraphDescriptor. And for each NodeDescripor I can loop through all it's LinkDescriptors,set this Node as source and create a new Node as destination. And so on until the last Node, but at the end I will have separate "sub systems" (each iteration): a node connected with its nodes's destinations for each iteration but not a whole interconnected system, as I don't know how to link them.
I also thought about creating a new class, that has a Node and a NodeDescriptor for example.
EDIT: My proposed solution:
public class TEST {
public static void main(String[] args) {
GraphDescriptor graphD = new GraphDescriptor();
Set<NodeDescriptor> nodesD = new HashSet<NodeDescriptor>();
//NODE1
NodeDescriptor nodeD1 = new NodeDescriptor();
NodeDescriptor nodeD2 = new NodeDescriptor();
NodeDescriptor nodeD3 = new NodeDescriptor();
Set<LinkDescriptor> linksD1 = new HashSet<LinkDescriptor>();
Set<LinkDescriptor> linksD2 = new HashSet<LinkDescriptor>();
Set<LinkDescriptor> linksD3 = new HashSet<LinkDescriptor>();
LinkDescriptor linkD12 = new LinkDescriptor();
LinkDescriptor linkD13 = new LinkDescriptor();
//LINKD12
linkD12.setSourceNode(nodeD1);
linkD12.setDestinationNode(nodeD2);
//LINK13
linkD13.setSourceNode(nodeD1);
linkD13.setDestinationNode(nodeD3);
linksD1.add(linkD12);
linksD1.add(linkD13);
nodeD1.setLinks(linksD1);
//NODE2
LinkDescriptor linkD23 = new LinkDescriptor();
linkD23.setSourceNode(nodeD2);
linkD23.setDestinationNode(nodeD3);
linksD2.add(linkD23);
nodeD2.setLinks(linksD2);
//NODE3
LinkDescriptor linkD31 = new LinkDescriptor();
linkD31.setSourceNode(nodeD3);
linkD31.setDestinationNode(nodeD1);
linksD3.add(linkD31);
nodeD3.setLinks(linksD3);
nodesD.add(nodeD1);
nodesD.add(nodeD2);
nodesD.add(nodeD3);
graphD.setNodes(nodesD);
MyGraph mygraph = convertGraph(graphD, "myGraph");
System.out.println("MY GRAPH");
//print NODES
System.out.println("NODES");
for(Node node: mygraph.getNodes().getNode()){
System.out.println(node.getName());
}
//print LINKS
System.out.println();
for(Link link: mygraph.getLinks().getLink()) {
System.out.println(link.getName()+" Source: "+link.getSource()+" Destination: "+ link.getDestination() );
}
}
public static MyGraph convertGraph(GraphDescriptor graphD, String name) {
MyGraph myGraph = new MyGraph();
Nodes nodes = new Nodes();
Links links = new Links();
Map<NodeDescriptor,String> nodeDName = new HashMap<NodeDescriptor,String>();
myGraph.setName(name);
int nodeN = 1;
for(NodeDescriptor nodeD : graphD.getNodes()) {
Node node = new Node();
node.setName("Node"+nodeN);
nodes.getNode().add(node);
nodeDName.put(nodeD, node.getName());
nodeN++;
}
int linkN = 1;
for(NodeDescriptor nodeD : graphD.getNodes()) {
for (LinkDescriptor linkD : nodeD.getLinks()) {
Link link = new Link();
link.setName("Link"+linkN);
link.setDestination(nodeDName.get(linkD.getDestinationNode()));
link.setSource(nodeDName.get(linkD.getSourceNode()));
linkN++;
links.getLink().add(link);
}
}
myGraph.setLinks(links);
myGraph.setNodes(nodes);
return myGraph;
}
}

Sorting int field of the wrapper class spring

I have a Navigation class where I am dynamically creating the navigation I am having two tables folder(it is directory that contains files) and content(it is like files or pages that will render the content on the public site). I have created a Navigation class in which I am having a wrapper class for merging the fields of content into the folder. I have tried using #OrderBy and #OrderColumn but I came to know that it will only work with collections.
List<Folder> folder = folderRepository.findAllByNavDepthLessThanOrderByNavDepthAsc(3);
here I am sorting it with navDepth(this column belongs to Folder entity) I also want to sort it with navOrder(this column belongs to Content entity)
#Service
public class NavigationService {
#Qualifier("jdbcMySQL")
private JdbcTemplate jdbcTemplate;
private FolderRepository folderRepository;
private FolderService folderService;
#Autowired
public NavigationService(JdbcTemplate jdbcTemplate,
FolderRepository folderRepository,
FolderService folderService) {
this.jdbcTemplate = jdbcTemplate;
this.folderRepository = folderRepository;
this.folderService = folderService;
}
#Transactional(propagation=Propagation.REQUIRED, readOnly=false)
public Map<String, NavigationItem> navigationItems() {
// TODO: // CROSS cutting AOP springs
// TODO: http://docs.spring.io/spring/docs/4.2.0.BUILD-SNAPSHOT/spring-framework-reference/htmlsingle/#aop
List<Folder> folder = folderRepository.findAllByNavDepthLessThanOrderByNavDepthAsc(3);
// List<Folder> folder = folderService.navigation();
Map<String, NavigationItem> navItems = new LinkedHashMap<String, NavigationService.NavigationItem>();
for (int i = 0; i < folder.size(); i++) {
NavigationItem ni = new NavigationItem();
ni.setNavDepth((int) (folder.get(i).getNavDepth()));
ni.setFileNamePath(folder.get(i).getDirectoryPath());
ni.setFilepath(folder.get(i).getDirectoryPath());
ni.setChildren(folder.get(i).getContent());
for (int k = 0; k < folder.size(); k++) {
if(folder.get(i).getId() == folder.get(k).getParentId()) {
ni.addSubFolder(folder.get(k));
System.out.println(folder.get(i).getTitle());
System.out.println(folder.get(k));
System.out.println("---!!!!!!________----------!!!!!!!!");
}
}
navItems.put(folder.get(i).getTitle(), ni);
}
return navItems;
}
public class NavigationItem {
private long id;
private long parentId;
private String title;
private String fileName;
private String fileNamePath;
private int navDepth;
private int navOrder;
private String parentFileName;
private String filePath;
private String folderName;
#OrderColumn(name="navOrder ASC")
private List<Content> children = new ArrayList();
private ArrayList<Folder> subFolder = new ArrayList();
public void setSubFolder(ArrayList<Folder> subFolder) {
this.subFolder = subFolder;
}
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
public String getFolderName() {
return folderName;
}
public void setFolderName(String folderName) {
this.folderName = folderName;
}
public ArrayList<Folder> getSubFolder() {
return subFolder;
}
public void addSubFolder(Folder subFolder) {
this.subFolder.add(subFolder);
}
public void setChildren(List<Content> list) {
this.children = list;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public long getParentId() {
return parentId;
}
public void setParentId(long parentId) {
this.parentId = parentId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getFileNamePath() {
return fileNamePath;
}
public void setFileNamePath(String fileNamePath) {
this.fileNamePath = fileNamePath;
}
public long getNavDepth() {
return navDepth;
}
public void setNavDepth(int navDepth) {
this.navDepth = navDepth;
}
public long getNavOrder() {
return navOrder;
}
public void setNavOrder(int navOrder) {
this.navOrder = navOrder;
}
public String getParentFileName() {
return parentFileName;
}
public void setParentFileName(String parentFileName) {
this.parentFileName = parentFileName;
}
public List<Content> getChildren() {
return children;
}
public void addChild(Content child) {
children.add(child);
}
public String getFilepath() {
return filePath;
}
public void setFilepath(String filePath) {
this.filePath = filePath;
}
}
}
Use a Comparator<NavigationItem> and pass that to Collections.sort() or similar methods.
The comparator might look like this:
class NavComparator implements Comparator<NavigationItem> {
int specialValueNoChildren = -1; //assuming nav_order is always 0 or greater
int compare(NavigationItem o1, NavigationItem o2) {
int max1 = getMaxNavOrder( o1 );
int max2 = getMaxNavOrder( o2 );
return Integer.compare( max1, max2 );
}
int getMaxNavOrder( NavigationItem ni ) {
int max = specialValueNoChildren;
for( Content child : ni.getChildren() ) {
max = Math.max(max, child.getNavOrder());
}
return max;
}
}
Here the maximum nav order of all children is selected with -1 being the special case of no children. Then the items are compared by their respective children's maximum nav order.
If you need a different order change that accordingly, e.g. by reversing max1 and max2 or by getting the lowest nav order of the children etc.

Add ArrayList into another ArrayList

I have two classes:
Products:
01; Desinfectante
02; Aerosol
03; Limpia Vidrio
04; Desengrasante
05; Mata mosquitos
06; Mata cucarachas
07; Aceite en aerosol
Instructions:
01;1;Elevar la masa hasta llegar a tal punto;0;10
01;1;Mezclar este material con anterior;1;15
01;2;Relevar;2;5
01;3;Llevar;00;0
02;1;Descripcion;7;2
02;2;Descripcion;6;2
02;2;Descripcion;00;0
03;1;Descripcion;1;1
03;1;Descripcion;2;9
03;2;Descripcion;00;0
03;3;Descripcion;5;2
03;4;Descripcion;6;2
03;4;Descripcion;3;10
04;1;Descripcion;00;0
04;2;Descripcion;1;2
04;3;Descripcion;1;0
04;3;Descripcion;2;2
04;3;Descripcion;3;2
04;4;Descripcion;7;1
04;4;Descripcion;6;2
05;1;Descripcion;7;20
05;1;Descripcion;6;9
05;2;Descripcion;00;0
05;3;Descripcion;1;2
05;3;Descripcion;2;10
06;1;Descripcion;2;12
06;1;Descripcion;4;1
06;1;Descripcion;6;8
06;2;Descripcion;5;4
06;2;Descripcion;7;2
07;1;Descripcion;1;12
07;1;Descripcion;2;2
07;2;Descripcion;3;19
07;2;Descripcion;4;4
07;2;Descripcion;00;2
07;2;Descripcion;5;12
The thing is this: i have to insert the instructions ArrayList into the Products. The link between them is the first number, that is the code of the product.
I tried two things, the first one:
public static ArrayList<Productos> InsertInstInProd(ArrayList<Instrucciones> instructions, ArrayList<Productos> products)
{
for (int i = 0; i < products.size()-1; i++)
{
int n = 0;
for (int j = 0; j < instructions.size()-1; j++)
{
int first = products.get(i).getNumero();
int second = instructions.get(j).getCodProd();
if (first == second)
{
products.get(i).getInstr().get(n).setCodIns(instructions.get(j).getCodIns());
products.get(i).getInstr().get(n).setCodProd(instructions.get(j).getCodProd());
products.get(i).getInstr().get(n).setDescr(instructions.get(j).getDescr());
products.get(i).getInstr().get(n).setMat(instructions.get(j).getMat());
products.get(i).getInstr().get(n).setMatNec(instructions.get(j).getMatNec());
n++;
}
}
n = 0;
}
The second one:
public static ArrayList<Productos> InsertInstInProd(ArrayList<Instrucciones> instructions, ArrayList<Productos> products)
{
for (int i = 0; i < products.size()-1; i++)
{
int n = 0;
for (int j = 0; j < instructions.size()-1; j++)
{
int first = products.get(i).getNumero();
int second = instructions.get(j).getCodProd();
if (first == second)
{
products.get(i).setInstr(instructions);
n++;
}
}
n = 0;
}
return products;
}
You are getting NullPointerException because of
products.get(i).getInstr().get(n).setCodIns(instructions.get(j).getCodIns());
You are not checking whether the list products.get(i).getInstr() has elements or not. When the list is empty and when you are accessing it as products.get(i).getInstr().get(0) it's throwing you NullPointerException because trying to get the first element of an empty list. So before you do this operation, make sure that products.get(i).getInstr() is not empty.
If they are of same type, you can directly add the whole arraylist :
products.get(i).getInstr().addAll(instructions); // again make sure that is not empty.
If you just want to replac, use :
products.get(i).setInstr(instructions.get(j));
Products Class
package productsandinstructions;
import java.util.List;
public class Product {
private int productId;
private String productName;
private List instructions;
public int getProductId() {
return productId;
}
public void setProductId(int productId) {
this.productId = productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public List getInstructions() {
return instructions;
}
public void setInstructions(List instructions) {
this.instructions = instructions;
}
}
Instruction Class
package productsandinstructions;
public class Instruction {
private int productId;
private int instructionId;
private String instDesc;
private int mat;
private int matNec;
private boolean done;
public int getProductId() {
return productId;
}
public void setProductId(int productId) {
this.productId = productId;
}
public int getInstructionId() {
return instructionId;
}
public void setInstructionId(int instructionId) {
this.instructionId = instructionId;
}
public String getInstDesc() {
return instDesc;
}
public void setInstDesc(String instDesc) {
this.instDesc = instDesc;
}
public int getMat() {
return mat;
}
public void setMat(int mat) {
this.mat = mat;
}
public int getMatNec() {
return matNec;
}
public void setMatNec(int matNec) {
this.matNec = matNec;
}
public boolean isDone() {
return done;
}
public void setDone(boolean done) {
this.done = done;
}
}
Main Class
package productsandinstructions;
import java.util.List;
public class ProductsAndInstructionsMain {
private List products;
private List instructions;
public List getProducts() {
return products;
}
public void setProducts(List products) {
this.products = products;
}
public List getInstructions() {
return instructions;
}
public void setInstructions(List instructions) {
this.instructions = instructions;
}
public static void main(String[] args) {
ProductsAndInstructionsMain main = new ProductsAndInstructionsMain();
main.mergeProductsAndInstructions();
}
public void mergeProductsAndInstructions() {
for (Product product : products) {
for (Instruction instruction : instructions) {
if ((!(instruction.isDone())) && (instruction.getProductId() == product.getProductId())) {
product.getInstructions().add(instruction);
instruction.setDone(true);
}
}
}
}
}

How to generate and print a tree from string in Java

I would like to create and print a tree from string which read from file. I tried the following code but I could not print the tree in a correct way.
I have file file.txt which has for example the following string
com-bo-news-2012,12
com-bo-news-2015,3
net-php-www,20
net-phototrails,3
I would like to create a tree like
root
|
com(17) //calculated as (2+12+3)
|bo(17)
|news(17)
|2012 (12)
|2015(3)
|net(23)
|php(20)
|www(20)
|phototrails(3)
I tried the following code
public void ReadFile(String inputFile){
Map<String[],Integer> map = new HashMap<String[], Integer>();
BufferedReader br=null;
String file1 = "";
try {
br = new BufferedReader(new FileReader(inputFile));
while ((file1 = br.readLine()) != null) {
String path[]=file1.split(",");
String nodes[]=path[0].split("-");
map.put(nodes,Integer.parseInt(path[1].trim()));
}
buildTree(map);
br.close();
}catch(Exception e){
System.out.println(e);
}
}
public void buildTree(Map<String[],Integer> map)
{
Map<String, Node> wordMap = new HashMap<String, Node>();
Node root = new Node();
for (Map.Entry<String[], Integer> entry : map.entrySet()) {
String key[] = entry.getKey();
Integer value = entry.getValue();
Node current=root;
Node p;
for(String node:key)
{
if(wordMap.containsKey(node)){
p = wordMap.get(node);
p.addCost(value);
} else {
p=new Node(node,value);
wordMap.put(node, p);
System.out.println("AddNode: "+p.getName());
}
current.addChild(p);
current = p;
}
}
printTree(root);
}
public void printTree(Node doc) { ///print tree
if (doc == null) {
System.out.println("Nothing to print!!");
return;
}
try {
System.out.println(doc.getName() + " " + doc.getCount());
List<Node> cl = doc.getChildren();
for (int i = 0; i < cl.size(); i++) {
Node node = cl.get(i);
System.out.println(
"\t" + node.getName() + " ->" + node.getCount());
}
List<Node> nl = doc.getChildren();
for (int i = 0; i < nl.size(); i++) {
Node node = nl.get(i);
printTree(node);
}
} catch (Throwable e) {
System.out.println("Cannot print!! " + e.getMessage());
}
}
public class Node {
private String name;
private int count;
private List<Node> children;
public Node() {
this(null, 0);
}
public Node(String name, int count) {
this.name = name;
this.count = count;
this.children = new ArrayList<Node>();
}
public Node(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public List<Node> getChildren() {
return children;
}
public void setChildren(List<Node> children) {
this.children = children;
}
public void addChild(Node n) {
for (Node nn : children) {
if (nn.name.equals(n.name)) {
return;
}
}
this.children.add(n);
}
public void addCost(int i) {
this.count += i;
}
}
But I could not print the tree in a correct way which mentioned. It sometimes make a infinite loop when it will get same node as a child. Could anyone please guide me for that? Thanks.
I have added the code to generate the Tree kind of structure, have used the composite pattern.
package com.test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class TestMain {
public static void main(String[] args) {
TestMain testMain = new TestMain();
List<String> testData = new ArrayList<String>();
testData.add("com-bo-news-2012,12");
testData.add("com-bo-news-2015,3");
testData.add("net-php-www,20");
testData.add("net-phototrails,3");
MyNode myNode = new MyNode("ROOT");
for (String string : testData) {
List<String> l = new ArrayList<String>();
l.addAll(Arrays.asList(string.split("-")));
testMain.buildTree(l, myNode);
}
printTree(myNode, 1);
}
private void buildTree(List<String> nodeNames, MyNode node) {
if (nodeNames.isEmpty()) {
return;
}
String nodeName = nodeNames.remove(0);
MyNode myNode = new MyNode(nodeName);
int index = node.getNodes().indexOf(myNode);
if (index == -1) {
node.getNodes().add(myNode);
} else {
myNode = node.getNodes().get(index);
}
buildTree(nodeNames, myNode);
}
private static void printTree(MyNode myNode, int tabCount) {
for (int i = 0; i < tabCount; i++) {
System.out.print("\t");
}
System.out.print(myNode.getNode() + "\n");
for (int i = 0; i < tabCount; i++) {
System.out.print("\t");
}
System.out.println("|");
for (MyNode node : myNode.getNodes()) {
printTree(node, ++tabCount);
}
}
}
package com.test;
import java.util.ArrayList;
import java.util.List;
public class MyNode {
private String node;
private List<MyNode> nodes;
public MyNode(String node) {
super();
this.node = node;
this.nodes = new ArrayList<MyNode>();
}
public MyNode(String node, List<MyNode> nodes) {
super();
this.node = node;
this.nodes = nodes;
}
public String getNode() {
return node;
}
public void setNode(String node) {
this.node = node;
}
public List<MyNode> getNodes() {
return nodes;
}
public void setNodes(List<MyNode> nodes) {
this.nodes = nodes;
}
#Override
public int hashCode() {
return node.hashCode();
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass().equals(obj.getClass())) {
return ((MyNode) obj).getNode().equals(node);
}
return false;
}
#Override
public String toString() {
return node + "[" + nodes.size()+"]";
}
}
Output needs to be formatted a bit, let me know if you have any questions

Sorting values with Comparator changes all the values with that object

I am working in an android application I want to sort a List of Objects with an Object Property. I have sorted it successfully but when I sort it all the List with that object changes the value to same as the sorted value
Please look into ma code :
SortedSet<Caseload> removeDuplicateClientName = new TreeSet<Caseload>(
new Comparator<Caseload>() {
#Override
public int compare(Caseload caseload0, Caseload caseload1) {
return caseload0.ClientName.compareTo(caseload1.ClientName);
}
});
// Getting the list of values from web service
mLISTCaseloadsHeads = parsedXML.getCaseLoadValues("get_Caseload_ClientServiceGroupID", param);
List<Caseload> newBackUp=mLISTCaseloadsHeads ;
Iterator<Caseload> iterator = mCaseloadsHeads.iterator();
while (iterator.hasNext()) {
removeDuplicateClientName.add(iterator.next());
}
mCaseloadsHeads.clear();
mCaseloadsHeads.addAll(removeDuplicateClientName);
The List newBackUp also changes the value to the same as sorted List
Caseload class:
public class Caseload implements Comparable<Caseload> {
public int BusClientLogID;
public int ClientID;
public int ClientStatus;
public int ClientServiceGroup_ClientSiteTherapyID;
public String ClientName;
public String TimeArrive;
public String TimeDepart;
public String SignOutTime;
public String SignInTime;
public String ServiceCompletedCount;
public Boolean ShowFooter = false;
public int getBusClientLogID() {
return BusClientLogID;
}
public void setBusClientLogID(int busClientLogID) {
BusClientLogID = busClientLogID;
}
public int getClientID() {
return ClientID;
}
public void setClientID(int clientID) {
ClientID = clientID;
}
public int getClientStatus() {
return ClientStatus;
}
public void setClientStatus(int clientStatus) {
ClientStatus = clientStatus;
}
public int getClientServiceGroup_ClientSiteTherapyID() {
return ClientServiceGroup_ClientSiteTherapyID;
}
public void setClientServiceGroup_ClientSiteTherapyID(
int clientServiceGroup_ClientSiteTherapyID) {
ClientServiceGroup_ClientSiteTherapyID = clientServiceGroup_ClientSiteTherapyID;
}
public String getClientName() {
return ClientName;
}
public void setClientName(String clientName) {
ClientName = clientName;
}
public String getTimeArrive() {
return TimeArrive;
}
public void setTimeArrive(String timeArrive) {
TimeArrive = timeArrive;
}
public String getTimeDepart() {
return TimeDepart;
}
public void setTimeDepart(String timeDepart) {
TimeDepart = timeDepart;
}
public String getSignOutTime() {
return SignOutTime;
}
public void setSignOutTime(String signOutTime) {
SignOutTime = signOutTime;
}
public String getSignInTime() {
return SignInTime;
}
public void setSignInTime(String signInTime) {
SignInTime = signInTime;
}
public String getServiceCompletedCount() {
return ServiceCompletedCount;
}
public void setServiceCompletedCount(String serviceCompletedCount) {
ServiceCompletedCount = serviceCompletedCount;
}
#Override
public int compareTo(Caseload compareCaseload) {
int busClientLogID = ((Caseload) compareCaseload).getBusClientLogID();
return busClientLogID - this.BusClientLogID;
}
}
Please give me a solution.
I doubt the return statement associated with your compare function in the comparator.
You should go by this approach to get the right ordering :
#Override
public int compare(YourClass lhs, YourClass rhs) {
YourClass p1 = (YourClass) lhs;
YourClass p2 = (YourClass) rhs;
int first = p1.ClientName; //use your getter if you want
int second = p2.ClientName;
if (second < first) {
return 1;
}
else if (second > first) {
return -1;
}
else {
return 0;
}
}
If you go by this approach I guess you will get the required ordering after sort.
Edit:
Now I have got the issue, you are using a reference of the original list in newBackup and its not a new list that is why this is happening, use this and you are good to go.
List<Caseload> newBackUp=new ArrayList<Caseload>(mLISTCaseloadsHeads);

Categories