Map (with operation) Stream java 8, nestedList - java

I'm looking for minimumlistPerValueOld working translate to minimumlistPerValueNew in the method getOptimizedTreeNodeResample(TreeNodeResample in, List<Integer> listSampleRateFinal)
/*I need to find the list that by adding it to the nested list,
the minimum number of operations required*/
private static TreeNodeResample getOptimizedTreeNodeResample(TreeNodeResample in, List<Integer> listSampleRateFinal) {
TreeNodeResample out = new TreeNodeResample(null);
listSampleRateFinal.forEach(sampleRateFinal -> {
List<List<NodeResample>> nestedListPerValue = getFilteredNestedListsValue(in, sampleRateFinal);
Long lastMinimum = Long.MAX_VALUE;
List<NodeResample> minimumlistPerValue = null;
for (List<NodeResample> listPerValue : nestedListPerValue) {
Long accumulator = addCalc(out.getNestedListsValue(), listPerValue)
.stream()
.map(nodeResample -> (long) nodeResample.getNumResampleOperations())
.mapToLong(Long::longValue).sum();
if (accumulator < lastMinimum) {
lastMinimum = accumulator;
minimumlistPerValue = listPerValue;
}
}
out.addListValue(minimumlistPerValue);
});
return out;
}
I believe I need to map listPerValue, as you can see listPerValue is the type List<NodeResample>
listPerValue -> {
TreeNodeResample temp = new TreeNodeResample(null);
temp.setNestedListsValue(out.getNestedListsValue());
temp.addListValue(listPerValue);
return temp.getListNodes();// return List<TreeNodeResample> type
}
Or map (to the same object type)
listPerValue -> {
TreeNodeResample temp = new TreeNodeResample(null);
temp.setNestedListsValue(out.getNestedListsValue());
temp.addListValue(listPerValue);
List<NodeResample> childsValues = temp.getListNodes()
.stream()
.map(node -> node.getValue())
.collect(Collectors.toList());
return childsValues;// return List<NodeResample> type
}
The complete TreeNodeResample class:
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
public class TreeNodeResample {
TreeNodeResample parent;
List<TreeNodeResample> children;
NodeResample value;
public TreeNodeResample(TreeNodeResample parent) {
this.parent = parent;
children = new ArrayList<>();
}
public TreeNodeResample(TreeNodeResample parent, NodeResample value) {
this.parent = parent;
children = new ArrayList<>();
this.value = value;
}
public void addChild(TreeNodeResample node) {
if (node != null && node.getValue() != null) {//REVIEW (node.getValue() != null) is needed?
if (children.stream().noneMatch(child -> Objects.equals(child.getValue(), node.getValue()))) {
children.add(node);
}
}
}
public TreeNodeResample getParent() {
return parent;
}
public void cleanChildren() {
children = new ArrayList<>();
}
public int getChildrenCount() {
return children.size();
}
public TreeNodeResample getChildrenAt(int position) {
if (children.size() > position && position > -1) {
return children.get(position);
}
return null;
}
public List<TreeNodeResample> getChildren() {
return children;
}
public NodeResample getValue() {
return value;
}
public boolean isLeaf() {
return (children.isEmpty());
}
public List<TreeNodeResample> getLeafs() {
return getLeafs(this);
}
public void addListValue(List<NodeResample> listValue) {
addListValue(this, listValue);
}
public TreeNodeResample getNode(NodeResample value) {
return getNode(this, value);
}
public List<NodeResample> getListValues() {
return getListNodes().stream().map(node -> node.getValue()).collect(Collectors.toList());
}
public List<TreeNodeResample> getListNodes() {
List<TreeNodeResample> listNodes = new ArrayList<>();
getListNodes(this, listNodes);
return listNodes;
}
public List<List<NodeResample>> getNestedListsValue() {
return getNestedListsValue(this);
}
public void setNestedListsValue(List<List<NodeResample>> nestedListsValue) {
setNestedListsValue(this, nestedListsValue);
}
public List<List<NodeResample>> getFilteredNestedListsValue(int sampleRateTarget) {
return getFilteredNestedListsValue(this, sampleRateTarget);
}
public TreeNodeResample getOptimizedTreeNodeResample(List<Integer> listSampleRateFinal) {
return getOptimizedTreeNodeResample(this, listSampleRateFinal);
}
public static void addListValue(TreeNodeResample parent, List<NodeResample> listValue) {
if (listValue != null) {
TreeNodeResample node = parent;
for (NodeResample child : listValue) {
node = getNode(node, child);
}
}
}
public static TreeNodeResample getNode(TreeNodeResample parent, NodeResample value) {
if (parent != null) {//REVIEW (value != null) is needed?
TreeNodeResample node = parent.getChildren().stream()
.filter(child -> child != null)
.filter(child -> Objects.equals(child.getValue(), value))
.findAny().orElse(null);
if (node != null) {
return node;
}
node = new TreeNodeResample(parent, value);
parent.addChild(node);
return node;
} else {
return null;
}
}
public static List<TreeNodeResample> getListNodes(TreeNodeResample parent) {
List<TreeNodeResample> listNodes = new ArrayList<>();
getListNodes(parent, listNodes);
return listNodes;
}
public static void getListNodes(TreeNodeResample parent, List<TreeNodeResample> listNodes) {
if (parent != null) {
listNodes.add(parent);
parent.getChildren().forEach(child -> getListNodes(child, listNodes));
}
}
public static List<List<NodeResample>> getNestedListsValue(TreeNodeResample parent) {
List<TreeNodeResample> listLeafs = getLeafs(parent);
List<List<NodeResample>> nestedListsValues = listLeafs.stream()
.map(leaf -> getParentsListValue(leaf))
.peek(listNodeResample -> {
//System.out.println(Arrays.toString(listNodeResample.toArray()) + System.lineSeparator() + System.lineSeparator());
})
.collect(Collectors.toList());
return nestedListsValues;
}
public static void setNestedListsValue(TreeNodeResample parent, List<List<NodeResample>> nestedListsValue) {
parent.cleanChildren();
nestedListsValue.stream()
.forEachOrdered(listValue -> {
addListValue(parent, listValue);
});
}
public static List<NodeResample> getParentsListValue(TreeNodeResample leaf) {
List<NodeResample> listValue = new ArrayList<>();
if (leaf != null) {
listValue.add(leaf.getValue());
TreeNodeResample node = leaf.getParent();
while (node != null && node.getValue() != null) {
listValue.add(0, node.getValue());
node = node.getParent();
}
}
return listValue;
}
public static List<List<NodeResample>> getFilteredNestedListsValue(TreeNodeResample parent, int sampleRateTarget) {
List<TreeNodeResample> listNodes = getListNodes(parent)
.stream()
.filter(treeNodeResample -> treeNodeResample.getValue() != null)
.filter(treeNodeResample -> treeNodeResample.getValue().getSampleRateTarget() == sampleRateTarget)
.collect(Collectors.toList());
List<List<NodeResample>> nestedListsValues = listNodes.stream()
.map(node -> getParentsListValue(node))
.collect(Collectors.toList());
return nestedListsValues;
}
private static TreeNodeResample getOptimizedTreeNodeResample(TreeNodeResample in, List<Integer> listSampleRateFinal) {
TreeNodeResample out = new TreeNodeResample(null);
listSampleRateFinal.forEach(sampleRateFinal -> {
List<List<NodeResample>> nestedListPerValue = getFilteredNestedListsValue(in, sampleRateFinal);
Long lastMinimum = Long.MAX_VALUE;
List<NodeResample> minimumlistPerValue = null;
for (List<NodeResample> listPerValue : nestedListPerValue) {
Long accumulator = addCalc(out.getNestedListsValue(), listPerValue)
.stream()
.map(nodeResample -> (long) nodeResample.getNumResampleOperations())
.mapToLong(Long::longValue).sum();
if (accumulator < lastMinimum) {
lastMinimum = accumulator;
minimumlistPerValue = listPerValue;
}
}
out.addListValue(minimumlistPerValue);
});
return out;
}
private static List<NodeResample> addCalc(List<List<NodeResample>> nestednestedListValue, List<NodeResample> listPerValue) {
TreeNodeResample temp = new TreeNodeResample(null);
temp.setNestedListsValue(nestednestedListValue);
temp.addListValue(listPerValue);
return temp.getListNodes().stream()
.map(node -> node.getValue())
.filter(nodeResample -> nodeResample != null)
.collect(Collectors.toList());
}
public static List<TreeNodeResample> getLeafs(TreeNodeResample parent) {
List<TreeNodeResample> listLeafs = new ArrayList<>();
getLeafs(parent, listLeafs);
return listLeafs;
}
private static void getLeafs(TreeNodeResample parent, List<TreeNodeResample> listLeafs) {
if (parent != null && listLeafs != null) {
if (parent.isLeaf()) {
listLeafs.add(parent);
} else {
parent.getChildren().forEach(child -> getLeafs(child, listLeafs));
}
}
}
#Override
public String toString() {
return "TreeNodeResample{" + "value=" + value + '}';
}
public static void tempPrintNested(List<List<NodeResample>> nestedListNodeResample) {
System.out.println(" List<List<NodeResample>> nestedListNodeResample = Arrays.asList(");
for (int o = 0; o < nestedListNodeResample.size(); o++) {
List<NodeResample> listNodeResample = nestedListNodeResample.get(o);
System.out.println(" Arrays.asList(");
for (int i = 0; i < listNodeResample.size(); i++) {
NodeResample nodeResample = listNodeResample.get(i);
if (nodeResample != null) {
System.out.print(" " + nodeResample.getCreator());
if (i < listNodeResample.size() - 1) {
System.out.println(",");
} else {
System.out.println("\n )");
}
}
}
if (o < nestedListNodeResample.size() - 1) {
System.out.println(" ,");
}
}
System.out.println(" );");
}
}
The another NodeResample class
public class NodeResample {
private int incrementL;
private int decrementM;
private int sampleRateSource;
private int sampleRateTarget;
private double maxPassFreq;
private Integer filterSize;
private Integer numResampleOperations;
public NodeResample(int incrementL, int decrementM, int sampleRateSource, int sampleRateTarget, double maxPassFreq, Integer filterSize, Integer numResampleOperations) {
this.incrementL = incrementL;
this.decrementM = decrementM;
this.sampleRateSource = sampleRateSource;
this.sampleRateTarget = sampleRateTarget;
this.maxPassFreq = maxPassFreq;
this.filterSize = filterSize;
this.numResampleOperations = numResampleOperations;
}
public int getIncrementL() {
return incrementL;
}
public void setIncrementL(int incrementL) {
this.incrementL = incrementL;
}
public int getDecrementM() {
return decrementM;
}
public void setDecrementM(int decrementM) {
this.decrementM = decrementM;
}
public int getSampleRateSource() {
return sampleRateSource;
}
public void setSampleRateSource(int sampleRateSource) {
this.sampleRateSource = sampleRateSource;
}
public int getSampleRateTarget() {
return sampleRateTarget;
}
public void setSampleRateTarget(int sampleRateTarget) {
this.sampleRateTarget = sampleRateTarget;
}
public double getMaxPassFreq() {
return maxPassFreq;
}
public void setMaxPassFreq(double maxPassFreq) {
this.maxPassFreq = maxPassFreq;
}
public Integer getFilterSize() {
return filterSize;
}
public void setFilterSize(Integer filterSize) {
this.filterSize = filterSize;
}
public Integer getNumResampleOperations() {
return numResampleOperations;
}
public void setNumResampleOperations(Integer numResampleOperations) {
this.numResampleOperations = numResampleOperations;
}
#Override
public String toString() {
return "NodeResample{" + "L=" + incrementL + ", M=" + decrementM
+ ", Source=" + sampleRateSource + ", Target=" + sampleRateTarget
+ ", filterSize=" + filterSize + ", numResampleOperations=" + numResampleOperations
+ "} ";
}
public String getCreator() {
return "new NodeResample(" + incrementL + "," + decrementM + "," + sampleRateSource + "," + sampleRateTarget + "," + "0.0" + "," + filterSize + "," + numResampleOperations
+ ")";
}
#Override
public int hashCode() {
int hash = 3;
return hash;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final NodeResample other = (NodeResample) obj;
if (this.incrementL != other.incrementL) {
return false;
}
if (this.decrementM != other.decrementM) {
return false;
}
if (this.sampleRateSource != other.sampleRateSource) {
return false;
}
if (this.sampleRateTarget != other.sampleRateTarget) {
return false;
}
if (!Objects.equals(this.filterSize, other.filterSize)) {
return false;
}
return true;
}
}
I want to translate using Java Streams
But, I'm frustrated...
List<NodeResample> minimumlistPerValueNew = nestedListPerValue.stream()
.min(
Comparator.comparingLong(map(listPerValue -> {
TreeNodeResample temp = new TreeNodeResample(null);
temp.setNestedListsValue(out.getNestedListsValue());
temp.addListValue(listPerValue);
return temp.getListNodes();
})
//.map(node -> node::getValue)
.filter(nodeResample -> nodeResample != null)
.mapToLong(NodeResample::getNumResampleOperations).sum())
)
.orElse(Collections.emptyList());
RESUMED SITUATION
public CustomObject wrapperMethod(List<CustomObject> listCustomObjects) {
Long lastMinimum = Long.MAX_VALUE;
CustomObject minCustomObject;
for (CustomObject customObject : listCustomObjects) {
Long returnedValue = anyMethodReturningLong(customObject);
if (returnedValue < lastMinimum) {
lastMinimum = returnedValue;
minCustomObject = customObject;
}
}
return minCustomObject;
}

You can try Stream.reduce() also for your problem.
What I understand from your problem is that there is a nestedList and out of those inner Lists you want to return the list which matches your minimum criteria.
For e.g let say we have nested list like this [[1,2,4],[5,6,7,8,9,10],[11,12]] and now you want return the list with smallest list.size(). Try below code :
import java.util.*;
import java.util.stream.*;
public class Main
{
public static void main(String[] args) {
List<List<Integer>> nestedList = Arrays.asList(
Arrays.asList(1,2,4),
Arrays.asList(5,6,7,8,9,2,5),
Arrays.asList(10,11,12,13,0));
Optional<List<Integer>> oplist = nestedList.stream()
.reduce((list1, list2) -> list1.size() < list2.size() ? list1 : list2);
oplist.ifPresent(System.out::println);
}
}
Output : [1,2,4]
Hope you get the idea behind the approach. Now you can try comparison check inside reduce method and check if it works for you.
Solution for RESUMED SITUATION
//Using .reduce() method
Optional<CustomObject> minCustomObjectList = listCustomObjects.stream()
.reduce((lastMinimum, returnedValue) -> anyMethodReturningLong(returnedValue) < anyMethodReturningLong(lastMinimum) ? returnedValue : lastMinimum);
minCustomObjectList.ifPresent(e -> System.out.println("Minimum Object using reduce method "+e.toString()));
//Using .min() method
CustomObject minCustomObject = listCustomObjects.stream()
.min(Comparator.comparingLong(e -> anyMethodReturningLong(e))).get();
System.out.printf("Minimum Object using min method"+minCustomObject.toString());

Related

Need help traversing an ArrayList of HashMap

I need to loop through an ArrayList and look for a particular "keys" HashMap and return the corresponding "params" HashMap as shown in the screenshot.
This is what I have so far but it's not working
private void getParam() {
List<Map<String, Object>> matrix = transactionInfoMatrix.getMatrixTransactionInfo();
MatrixTransactionInfoKeys key = new MatrixTransactionInfoKeys("OP/OP", "2777", "CT", "NBCTRANSFER", "AMT");
for (Map<String, Object> entry : matrix) {
if (entry.containsValue(key)) {
System.out.println("Found it");
}
}
}
Here is the MatrixTransactionInfoKeys class, but I have removed the getters and setters for the purposes of this post.
public class MatrixTransactionInfoKeys {
private String accountType;
private String applicationSourceCode;
private String operationType;
private String service;
private String transactionType;
public MatrixTransactionInfoKeys(String accountType, String applicationSourceCode, String operationType, String service, String transactionType) {
this.accountType = accountType;
this.applicationSourceCode = applicationSourceCode;
this.operationType = operationType;
this.service = service;
this.transactionType = transactionType;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((accountType == null) ? 0 : accountType.hashCode());
result = prime * result + ((applicationSourceCode == null) ? 0 : applicationSourceCode.hashCode());
result = prime * result + ((operationType == null) ? 0 : operationType.hashCode());
result = prime * result + ((service == null) ? 0 : service.hashCode());
result = prime * result + ((transactionType == null) ? 0 : transactionType.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
MatrixTransactionInfoKeys other = (MatrixTransactionInfoKeys) obj;
if (accountType == null) {
if (other.accountType != null) {
return false;
}
} else if (!accountType.equals(other.accountType)) {
return false;
}
if (applicationSourceCode == null) {
if (other.applicationSourceCode != null) {
return false;
}
} else if (!applicationSourceCode.equals(other.applicationSourceCode)) {
return false;
}
if (operationType == null) {
if (other.operationType != null) {
return false;
}
} else if (!operationType.equals(other.operationType)) {
return false;
}
if (service == null) {
if (other.service != null) {
return false;
}
} else if (!service.equals(other.service)) {
return false;
}
if (transactionType == null) {
return other.transactionType == null;
} else
return transactionType.equals(other.transactionType);
}
#Override
public String toString() {
return "MatrixTransactionInfoKeys [service=" + service + ", applicationSourceCode=" + applicationSourceCode
+ ", transactionType=" + transactionType + ", operationType=" + operationType + ", accountType=" + accountType + "]";
}
}
Remaking this answer, since I originally misinterpreted the question.
Based on the code supplied, assuming the MatrixTransactionInfoKeys in the map actually match and are created similarly, I get "Found it" in the output of this:
public class MatrixCheck {
public TransactionInfoMatrix transactionInfoMatrix;
private void getParam() {
List<Map<String, Object>> matrix = transactionInfoMatrix.getMatrixTransactionInfo();
MatrixTransactionInfoKeys key = new MatrixTransactionInfoKeys("OP/OP", "2777", "CT", "NBCTRANSFER", "AMT");
for (Map<String, Object> entry : matrix) {
if (entry.containsValue(key)) {
System.out.println("Found it");
}
}
}
public static void main( String[] args ) {
MatrixCheck matrixCheck = new MatrixCheck();
matrixCheck.transactionInfoMatrix = new TransactionInfoMatrix();
matrixCheck.transactionInfoMatrix.transactionInfo = new ArrayList<>();
matrixCheck.transactionInfoMatrix.transactionInfo.add( new HashMap<>() );
// Add the object to the map exactly as how it is
// constructed in the "getParam" portion
matrixCheck.transactionInfoMatrix.transactionInfo.get(0).put( "MyTest", new MatrixTransactionInfoKeys("OP/OP", "2777", "CT", "NBCTRANSFER", "AMT") );
matrixCheck.getParam();
}
static class TransactionInfoMatrix {
List<Map<String,Object>> transactionInfo;
public List<Map<String,Object>> getMatrixTransactionInfo() {
return transactionInfo;
}
}
static class MatrixTransactionInfoKeys {
private String accountType;
private String applicationSourceCode;
private String operationType;
private String service;
private String transactionType;
public MatrixTransactionInfoKeys(String accountType, String applicationSourceCode, String operationType, String service, String transactionType) {
this.accountType = accountType;
this.applicationSourceCode = applicationSourceCode;
this.operationType = operationType;
this.service = service;
this.transactionType = transactionType;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((accountType == null) ? 0 : accountType.hashCode());
result = prime * result + ((applicationSourceCode == null) ? 0 : applicationSourceCode.hashCode());
result = prime * result + ((operationType == null) ? 0 : operationType.hashCode());
result = prime * result + ((service == null) ? 0 : service.hashCode());
result = prime * result + ((transactionType == null) ? 0 : transactionType.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
MatrixTransactionInfoKeys other = (MatrixTransactionInfoKeys) obj;
if (accountType == null) {
if (other.accountType != null) {
return false;
}
} else if (!accountType.equals(other.accountType)) {
return false;
}
if (applicationSourceCode == null) {
if (other.applicationSourceCode != null) {
return false;
}
} else if (!applicationSourceCode.equals(other.applicationSourceCode)) {
return false;
}
if (operationType == null) {
if (other.operationType != null) {
return false;
}
} else if (!operationType.equals(other.operationType)) {
return false;
}
if (service == null) {
if (other.service != null) {
return false;
}
} else if (!service.equals(other.service)) {
return false;
}
if (transactionType == null) {
return other.transactionType == null;
} else
return transactionType.equals(other.transactionType);
}
#Override
public String toString() {
return "MatrixTransactionInfoKeys [service=" + service + ", applicationSourceCode=" + applicationSourceCode
+ ", transactionType=" + transactionType + ", operationType=" + operationType + ", accountType=" + accountType + "]";
}
}
}

Create Node tree from list of paths

I have this list of paths:
private static final List<String> paths = Arrays.asList(
"assets/css/custom.css",
"assets/css/default.css",
"assets/js/main.js",
"assets/js/old/main-old.js",
"fonts/poppins.woff",
"favicon.ico",
"index.html"
);
That I need to create a searchable tree, like this:
and here's what I have now:
public void testCreateTree() {
Node root = new Node("ROOT", null, Node.NODE_TYPE.ROOT);
paths.forEach(path -> {
final Node[] currentNode = {root};
if(!path.contains("/")) { // root files
currentNode[0].addChild(new Node(path, currentNode[0], Node.NODE_TYPE.FILE));
} else {
String folders = DirectoryRegex.matchFolders(path); // e.g. matches/returns "root/"
String fileName = DirectoryRegex.matchFile(path); // e.g. matches/returns index.html
String[] folderArrays = folders.split("/");
Arrays.asList(folderArrays).forEach(folder -> {
Node node = new Node("ROOT", null, Node.NODE_TYPE.ROOT);
node.setNodeName(folder);
node.setNodeType(Node.NODE_TYPE.FOLDER);
node.setParent(currentNode[0]);
// check if child exists
Node existingNode = currentNode[0].getChild(folder, Node.NODE_TYPE.FOLDER);
if(existingNode == null) {
existingNode = node;
currentNode[0].addChild(node);
}
currentNode[0] = existingNode;
});
currentNode[0].addChild(new Node(fileName, currentNode[0], Node.NODE_TYPE.FILE));
}
});
String print = root.printNodeJSON().toString();
Console.log(print);
}
The Node.java class is this:
public class Node {
public NODE_TYPE getNodeType() {
return nodeType;
}
public void setNodeType(NODE_TYPE nodeType) {
this.nodeType = nodeType;
}
public Node getParent() {
return parent;
}
public void setParent(Node parent) {
this.parent = parent;
}
public List<Node> getChildren() {
if(children == null) {
children = new LinkedList<>();
}
return children;
}
public void setChildren(List<Node> children) {
this.children = children;
}
public void addChild(Node child) {
getChildren().add(child);
}
public Node getChild(String nodeName, NODE_TYPE nodeType) {
final Node[] child = {null};
getChildren().forEach(node -> {
if(node.getNodeName().equals(nodeName) && node.getNodeType().equals(nodeType)) {
child[0] = node;
}
});
return child[0];
}
public String getNodeName() {
return nodeName;
}
public void setNodeName(String nodeName) {
this.nodeName = nodeName;
}
private Node() {}
public Node(String nodeName, Node parent, NODE_TYPE nodeType) {
setNodeName(nodeName);
setNodeType(nodeType);
setParent(parent);
}
public enum NODE_TYPE { FILE, FOLDER, ROOT }
private NODE_TYPE nodeType;
private Node parent;
private List<Node> children;
private String nodeName;
public String printNode() {
final String[] s = {"["};
s[0] = s[0] + "Node name: " + nodeName + ",";
if(nodeType != null) {
s[0] = s[0] + "Node type: " + nodeType.toString() + ",";
}
if(getParent() != null) {
s[0] = s[0] + "Node Parent: [ name = " + getParent().getNodeName() + ", type = " + getParent().getNodeType() + " ]";
}
s[0] = s[0] + "Node children: [";
getChildren().forEach(child -> {
s[0] = "[" + s[0] + child.printNode() + "]";
});
s[0] = s[0] + "]";
s[0] = s[0] + "]";
return s[0];
}
public JSONObject printNodeJSON() {
JSONObject jsonObject = new JSONObject();
jsonObject.put("nodeName", nodeName);
jsonObject.put("nodeType", nodeType != null ? nodeType.toString() : null);
jsonObject.put("parent", getParent() != null ? getParent().printNodeJSONWithoutChildren() : null);
JSONArray children = new JSONArray();
getChildren().forEach(child -> {
children.put(child.printNodeJSON());
});
jsonObject.put("children", children);
return jsonObject;
}
public JSONObject printNodeJSONWithoutChildren() {
JSONObject jsonObject = new JSONObject();
jsonObject.put("nodeName", nodeName);
jsonObject.put("nodeType", nodeType != null ? nodeType.toString() : null);
jsonObject.put("parent", getParent() != null ? getParent().printNodeJSONWithoutChildren() : null);
// JSONArray children = new JSONArray();
// getChildren().forEach(child -> {
// children.put(child.printNodeJSON());
// });
// jsonObject.put("children", children);
return jsonObject;
}
}
The code works fine but I want to know the most efficient way to do this.

Sorting a linkedList by the value of the object

For an assignment, I've been tasked to create a priority based support ticket system which contains the user's Name, ID, Handler and Priority however ticket's with higher priority are placed first in the list to be dealt with.
I have three classes.
Main: where I add/delete and change ticket priority.
TicketSystem: Contains the constructor for the ticket alongside getters and setter methods
LinkedList: Has insert, delete printList and should have sortList
So far I've determined the algorithm needs to be bubblesort as Priority is an int value but I'm not too sure how to receive the value for priority and then sort it.
public class TicketSystem {
private String handler;
private int priority;
private String iD;
private String creator;
public TicketSystem() {
}
public String getHandler ( ) {
return handler;
}
public int getPriority () {
return priority;
}
public String getID () {
return iD;
}
public String creator () {
return creator;
}
public void setID (String i) {
this.iD = i;
}
public void setHandler (String h) {
this.handler = h;
}
public void setPriority (int p ) {
this.priority = p;
}
public String setCreator (String c) {
return this.creator = c;
}
public void addTicket( String h, int p, String c, String iD) {
this.handler = h;
this.priority = p;
this.iD = iD;
this.creator = c;
}
#Override
public String toString() {
String output = "";
output += "Handler: " + handler +", ";
output += "Priority: " + priority + ", ";
output += "Creator: " + creator + ", ";
output += "ID: " + iD + " ";
return output;
}
}
public class LinkedList {
private Node head;
public LinkedList(TicketSystem ticket) {
head = new Node();
head.ticket = ticket;
head.link = null;
}
public boolean insertItem(TicketSystem ticket) {
Node n = new Node();
Node new_node;
new_node = head;
while (new_node.link != null) {
new_node = new_node.link;
}
n.ticket = ticket;
n.link = null;
new_node.link = n;
return true;
}
public void printList() {
Node z = head;
while (z!= null) {
System.out.println(z.ticket.toString());
z = z.link;
}
}
public boolean deleteItem(TicketSystem ticket) {
if(ticket.equals(head.ticket)) {
head = head.link;
return true;
} else {
Node prevNode = head;
Node curNode = head.link;
while(curNode != null && !(curNode.ticket == ticket)) {
prevNode = curNode;
curNode = curNode.link;
}
if(curNode != null) {
prevNode.link = curNode.link;
return true;
} else {
return false;
}
}
}
/* sort list */
public void sortList() {
TicketSystem ts = new TicketSystem();
}
class Node {
private TicketSystem ticket;
private Node link;
}
}

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

How can I split a line and assign index number for a graph's links connection in java?

I need help to generate a graph's link connection in json format which are index numbers. I can manage to generate the 1st part of nodes index numbers but can't do the 2nd part of links index numbers. Nodes index number should be plotted links index no. Anyone please help.
Input file:
Abdelaziz Bouteflika,Bush,1
Albert II of Belgium,Bush,1
Albert Wehrer,Bush,1
Berlusconi,Bush,1
Bernard-Montgomery,Bush,1
Bush,Fidel-Castro,1
Bernard-Montgomery,Albert Wehrer,5
Expected Output file:
{
"nodes":[
{"name":"Bush","Id":0},
{"name":"Abdelaziz Bouteflika","Id":1},
{"name":"Albert II of Belgium","Id":2},
{"name":"Albert Wehrer","Id":3},
{"name":"Berlusconi","Id":4},
{"name":"Bernard-Montgomery","Id":5},
{"name":"Fidel-Castro","Id":6}
],
"links":[
{"source":1,"target":0},
{"source":2,"target":0},
{"source":3,"target":0},
{"source":4,"target":0},
{"source":5,"target":0},
{"source":6,"target":0},
{"source":5,"target":3}
]
}
My code:
public class Link_Of_Index {
List<String> linklist1 = new ArrayList<String>();
List<String> finalList = new ArrayList<String>();
public void getIndexNo() throws IOException{
BufferedReader reader = new BufferedReader(new FileReader("E:/Workspace/Entity_Graph_Creation/WebContent/Graph_nodes_1.csv"));
FileWriter fw = new FileWriter(new File("E:/workspace/Entity_Graph_Creation/Input/links.json"));
try{
String line = null;
int index=0;
while (( line = reader.readLine()) != null)
{
String[] splits = line.split(",");
linklist1.add(splits[0]);
linklist1.add(splits[1]);
linklist1.add(splits[2]);
}
for (String s: linklist1) {
if (!finalList.contains(s)) {
finalList.add(s);
JSONObject obj = new JSONObject();
obj.put("Id", index);
obj.put("name", s);
fw.write(obj.toString()+ ","+ "\n");
index ++;
}
fw.flush();
}
}
catch (IOException ex){
ex.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
Link_Of_Index inx = new Link_Of_Index();
inx.getIndexNo();
}
}
EDIT: I rewrote the entire answer to reflect your new requirements. For the next time, you should mention that in first place, or make 2 seperate questions of it.
public class GraphFileIO {
private static final Comparator<Node> NODE_COMPARATOR = new Comparator<Node>() {
#Override
public int compare(Node node1, Node node2) {
return node1.compareTo(node2);
}
};
private Map<Node, List<Edge>> graph;
private final File sourceFile;
public GraphFileIO(final File pSource) throws IOException {
if (pSource.exists()) {
sourceFile = pSource;
} else {
throw new IOException();
}
}
public void readGraph() throws IOException {
int index = 1;
graph = new TreeMap<>(NODE_COMPARATOR);
for (String line : Files.readAllLines(sourceFile.toPath(), Charset.defaultCharset())) {
if (line.trim().isEmpty()) {
continue; // skip blank lines
}
// csv columns:
// node 1, node 2, weight, event
String[] splits = line.split(",");
Node n = new Node(index, splits[0]);
if (!graph.containsKey(n)) {
graph.put(n, new ArrayList<Edge>());
}
n = new Node(index, splits[0]);
if (!graph.containsKey(n)) {
graph.put(n, new ArrayList<Edge>());
}
Edge edge = new Edge(splits[3]);
for (Entry<Node, List<Edge>> entry : graph.entrySet()) {
Node node = entry.getKey();
if (node.getName().equals(splits[0])) {
edge.setSource(node.getId());
entry.getValue().add(edge);
} else if (node.getName().equals(splits[1])) {
edge.setTarget(node.getId());
// if edges are bi-directional, uncomment the next line of
// code
/* entry.getValue().add(edge); */
}
}
}
}
public void writeGraphToFile(final File targetFile) throws IOException {
JSONObject obj = new JSONObject();
JSONArray nodeList = new JSONArray();
JSONArray edgeList = new JSONArray();
for (Entry<Node, List<Edge>> entry : graph.entrySet()) {
JSONObject jsonNode = new JSONObject();
jsonNode.put("name", entry.getKey().getName());
jsonNode.put("Id", entry.getKey().getId());
jsonNode.put("event", entry.getValue());
nodeList.add(jsonNode);
for (Edge link : entry.getValue()) {
JSONObject link = new JSONObject();
link.put("source", link.getSourceID());
link.put("target", link.getTargetID());
edgeList.add(link);
}
}
obj.put("nodes", nodeList);
obj.put("links", edgeList);
FileWriter fw = new FileWriter(targetFile);
fw.write(obj.toJSONString());
fw.flush();
fw.close();
}
public static void main(final String[] args) {
File source = new File("C:\\Sandbox\\src\\foo\\test.csv");
File target = new File("C:\\Sandbox\\src\\foo\\testresult.csv");
GraphFileIO g;
try {
g = new GraphFileIO(source);
g.readGraph();
g.writeGraphToFile(target);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class Node implements Comparable<Node> {
private final Integer id;
public Integer getId() {
return id;
}
public String getName() {
return name;
}
private final String name;
private final Collection<String> events;
public Node(Integer id, String name) {
super();
this.id = id;
this.name = name;
this.events = new HashSet<>();
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
public Collection<String> getEvents() {
return events;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Node other = (Node) obj;
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
return true;
}
#Override
public int compareTo(Node o) {
return id.compareTo(o.id);
}
}
public class Edge {
private final String event;
private Integer sourceID;
private Integer targetID;
public Edge(String string) {
event = string;
}
public void setSource(Integer id) {
sourceID = id;
}
public void setTarget(Integer id) {
targetID = id;
}
#Override
public String toString() {
return event;
}
public Integer getSourceID() {
return sourceID;
}
public Integer getTargetID() {
return targetID;
}
public String getEvent() {
return event;
}
}

Categories