Comparing Two Objects and Storing the Result - java

I have two objects and compare their Strings using an algorithm. I need to store the result, the two objects and the best values. Any suggestions?
void getDistances(Class m1, Class m2) {
Vector[] vector1 = new Vector[m1.getSize()]; // Object from my class
Vector[] vector2 = new Vector[m2.getSize()]; // Object from my class
for (int i = 0; i < vector1.length; i++) {
Class current;
Class next;
current = m1.getInfo(i);
for (int j = 0; j < vector2.length; j++) {
prox = m2.getInfo(j);
calcDist = lev.distance(current.getLabel(), next.getLabel());
System.out.println(current + " <-> " + next + " = " + df.format(calcDist));
if(something here){
// I think it's here the logic ...
}
}
}
}
Any idea will help me. Thanks.

Related

Printing ArrayList without brackets Java [duplicate]

This question already has answers here:
What is a raw type and why shouldn't we use it?
(16 answers)
Closed 10 months ago.
I have an ArrayList and I'm trying to print it without the bracket ("[]") , I don't know where the problem lies , is it with how the ArrayList is initialized or is it the print method ?
The output that I'm getting :
S0 = (q0) = [0, 2]
S1 = (q1) = [1, 0]
S2 = (q2) = [2, 1]
The output that I'm trying to get :
S0 = (q0) = {q0, q2}
S1 = (q1) = {q1, q0}
S2 = (q2) = {q2, q1}
How can this be achieved ?
CODE :
import java.util.ArrayList;
import java.util.Scanner;
public class MyClass {
public static void printArray(String[][] data){
System.out.print(" ");
for (int i = 0; i < data[0].length; i++) {
System.out.print("q" + i + " ");
}
System.out.println();
for (int i=0;i< data.length;i++){
System.out.print("q" + i + " ");
for (int j=0;j< data[0].length;j++){
System.out.print(data[i][j] + " ");
}
System.out.println();
}
}
public static ArrayList findEpsilon(String[][] data){
ArrayList<ArrayList<Integer> > aList = new ArrayList<>();
ArrayList<Integer> a1;
for (int i = 0; i < data.length ; i++) {
a1 = new ArrayList<>();
//aList = new ArrayList<>();
a1.add(i);
for (int j = 0; j < data[0].length; j++) {
if (data[i][j].contains("eps")){
a1.add(j);
}
}
aList.add(a1);
}
return aList;
}
public static void printArrayList(ArrayList<ArrayList<Integer>> aList){
for (int i = 0; i < aList.size(); i++) {
for (int j = 0; j < aList.get(i).size(); j++) {
System.out.println("S" + j + " = (q" + j + ") = " + aList.get(i).get(j) + "
");
}
// System.out.println();
}
}
public static void main(String args[]) {
String[][] data = {
{ "a", "b", "eps"},
{ "eps", "a", "-" },
{ "a", "eps", "b"}};
ArrayList<ArrayList<Integer> > aList = new ArrayList<ArrayList<Integer> >(3);
printArray(data);
System.out.println("\n");
aList.add(findEpsilon(data));
printArrayList(aList);
}
}
The type of aList should be ArrayList<ArrayList<ArrayList<Integer>>>. The compiler doesn't complain about this because the findEpsilon method returns an ArrayList without type parameters. It's generally good practice to specify the generic type (i.e., findEpsilon should return ArrayList<ArrayList<ArrayList<Integer>>>). You will need to fix this in several places.
If you want to use curly brackets for the array, you can then use the following code:
for (int j = 0; j < aList.get(i).size(); j++) {
String listAsString = aList.get(i).get(j).stream().map(Object::toString).collect(Collectors.joining(",", "{", "}"));
System.out.println("S" + j + " = (q" + j + ") = " + listAsString + " ");
}
The stream iterates over each of the elements in the list and converts them to a string. The Collectors.joining collector then joins the individual strings by inserting a comma between them and placing curly brackets at the start and at the end.
You can define a Lambda to take a List<String> and convert it like you want.
put the list.toString version in a StringBuilder.
then change the first and last characters to { and } respectively
import java.util.function.Function;
Function<List<String>, String> fmt = lst-> {
StringBuilder sb = new StringBuilder(lst.toString());
sb.setCharAt(0,'{');
sb.setCharAt(sb.length()-1,'}');
return sb.toString();
};
Now apply a list to the lambda.
List<String> s = List.of("A","B","C");
System.out.println(fmt.apply(s));
prints
{A, B, C}

Bubble Sort Array with unknown length (Java)?

This is Java through my university so there are some components in here that you may not know. Do not pay attention for them because they are not the problem.
My compiler made me initialize my array to null. I then try to run the rest of my program and it said that it is supposed to work with an array that has actual values in it. My question is how should I go about doing this?
private static String[] alphabetSort(Map<String, Integer> mapWord) {
String[] ordered = null;
Map<String, Integer> copy = mapWord;
for (int i = 0; i < copy.size(); i++) {
Map.Pair<String, Integer> pair = copy.removeAny();
String key = pair.key();
ordered[i] = key;
}
boolean flag = true;
String temp;
while (flag) {
flag = false;
for (int j = 0; j < ordered.length; j++) {
String test1 = ordered[j];
String test2 = ordered[j + 1];
if (test1.compareTo(test2) < 0) {
temp = ordered[j];
ordered[j] = ordered[j + 1];
ordered[j + 1] = temp;
flag = true;
}
}
}
return ordered;
}
Arrays have fixed-size. You have to pick a size when you're creating it.
Try:
String[] ordered = new String[mapWord.size()];

Searching through parallel arrays

I am trying to write a program to search through parallel arrays on stores double values one string, I need to be able to search either by a certain value returning all values equal to or more than in the array and the same index in the string array.
I was able to write methods to sort the array like this
public static void Sortstrength(Double[] strength, String[] names, int sel) //method to sort beers alphabetically up and down
{
String tmpStr; //temp string to help sort array
Double tmpDbl; //temp double to help sort array
if (sel == 1) //sort by names ascending if sel int = 1
{
for (int t = 0; t < strength.length - 1; t++) {
for (int i = 0; i < strength.length - 1; i++) {
if (strength[i].compareTo(strength[i + 1]) > 0) {
tmpStr = names[i];
tmpDbl = strength[i];
names[i] = names[i + 1];
strength[i] = strength[i + 1];
names[i + 1] = tmpStr;
strength[i + 1] = tmpDbl;
}
}
}
for (int i = 0; i < names.length; i++) {
System.out.printf("%-15s %s \n", names[i], strength[i]);
}
} else //sort by names descending
{
for (int t = 0; t < strength.length - 1; t++) {
for (int i = 0; i < strength.length - 1; i++) {
if (strength[i].compareTo(strength[i + 1]) < 0) {
tmpStr = names[i];
tmpDbl = strength[i];
names[i] = names[i + 1];
strength[i] = strength[i + 1];
names[i + 1] = tmpStr;
strength[i + 1] = tmpDbl;
}
}
}
for (int i = 0; i < names.length; i++) {
System.out.printf("%-15s %s \n", names[i], strength[i]);
}
}
}
I have no clue how to alter this if it is even possible to do so but any help would be appreciated as I am pretty stuck
Thanks for any help.
Create a class Beer holding a double and a string value. Add the Beers to a list and use a Comperator to sort. Output the list.
public class Beer
{
private final double strength;
private final String name;
public Bear(final String name, final double strength)
{
this.strength = strength;
this.name = name;
}
public String getName() { return name; }
public double getStrength() { return strength; }
}
Sounds like what you actually want is a sorted map from Doubles to Strings. Use TreeMap:
private final TreeMap<Double, String> map = new TreeMap<>(); //for descending order use .reverseMap()
public SortedMap<Double, String> getKeysAbove(double key) {
return map.subMap(key, Double.POSITIVE_INFINITY);
}
public static void exampleUsage() {
Mapper mapper = new Mapper(); //or whatever class name
mapper.map.put(1D, "Goodbye");
mapper.map.put(2D, "Hello, ");
mapper.map.put(3D, "World!");
for (Entry<Double, String> e : mapper.getKeysAbove(1.5).entrySet()) {
System.out.println(e.getKey() + ": " + e.getValue());
}
}
To search your data with strength array sorted in ascended order use binarySearch:
double threshold = 2.0d;
int index = Arrays.binarySearch(strength, threshold);
if (index < 0) {
index = -index - 1;
}
since your two arrays are "synced" this index will match your String array.
Note, you could implement "binding" of strength/names data and their sorting much cleaner and more effectively in at least two different ways :
use Map to store your bindings assuming your strength keys are unique, and then sorting by keys.
Use helper POJO class MyData holding both strength and name, as in Hannes's answer and sort array of MyData objects supplying custom Comparator, then do binarySearch with same comparator to find index according to your requirements.

Displaying 2D array results excluding nulls in Java

I'm creating an array that will sort arrayString[10][2] and then display the results to the user using JOptionPane. The length of the 2D array is irrelevant, just note that it will not be completely populated resulting in nulls. When I display the information to the user I want to exclude the nulls. Currently I have used a variable "isNull" to make this work but I know it is inefficient and am looking for the proper way to accomplish this.
The Array with two rows of data
String arrayString[][] = new String[10][2];
arrayString[0][0] = "Doe";
arrayString[0][1] = "John";
arrayString[1][0] = "Doe";
arrayString[1][1] = "Jane";
The actual program logic
String output = "";
int isNull = 0;
for (int i = 0; i < arrayString.length; i++)
{
for (int j = 0; j < arrayString[i].length; j++)
{
if ( arrayString[i][j] == null )
{
isNull = 1;
break;
}
else
output += arrayString[i][j] + " ";
isNull = 0;
}
if(isNull == 1)
break;
else
output += " \n";
}
JOptionPane.showMessageDialog(null,output,"Results",JOptionPane.INFORMATION_MESSAGE);
Thanks for all the help guys, I wen't back through my code and reevaluated it and got an answered I'm satisfied with on my own. Thanks for the responses though.
Solved
for (int i = 0; i < arrayString.length; i++)
{
for (int j = 0; j < arrayString[i].length; j++)
{
if ( arrayString[i][0] == null)
break;
else
output += arrayString[i][j] + " ";
}
if ( arrayString[i][0] == null)
break;
else
output += " \n";
}
// Make a List of all anagram groups above size threshold.
List<List<String>> winners = new ArrayList<List<String>>();
for (List<String> l : m.values())
if (l.size() >= minGroupSize)
winners.add(l);
// Sort anagram groups according to size
Collections.sort(winners, new Comparator<List<String>>() {
public int compare(List<String> o1, List<String> o2) {
return o2.size() - o1.size();
}});
// Print anagram groups.
for (List<String> l : winners)
System.out.println(l.size() + ": " + l);
Look at this post more accurate:
http://docs.oracle.com/javase/tutorial/collections/algorithms/index.html#sorting

Reflection of an array in java

I'm fairly new to java and have come across a problem. My task is to create a class which contains a method write(Object obj) that writes the type of the object as well as the name and type of all attributes into a file. Recursion is involved since the object may have objects/arrays of objects as attributes.
Here is the code:
public void write(Object obj) throws Exception {
if(obj == null)
{
out.close();
return;
}
Class c = obj.getClass();
Class d;
Field fields_c[] = c.getDeclaredFields();
System.out.println("class_name:" + c.getName());
int i, j;
String tab = new String("");
for(i = 0; i < indent_level; i++)
{
tab = tab + "\t";
}
out.write(tab + "class_name:" + c.getName() + "\n");
for(i = 0; i < fields_c.length; i++) {
System.out.println("field name: " + fields_c[i].getName() + " ");
c = fields_c[i].getType();
fields_c[i].setAccessible(true);
if(c.isPrimitive()) {
out.write("\t" + tab + "field_name:" + c.toString() + "\n");
}
else if(c.isArray()) {
System.out.println("field of type array with elements of type:" + c.getComponentType());
for(j = 0; j < Array.getLength(c); j++)
{
d = Array.get(c, j).getClass();
indent_level = indent_level + 1;
this.write(d);
indent_level = indent_level - 1;
}
}
else
{
System.out.println("field is not primitive of type:" + c.getName());
Object foo = fields_c[i].get(obj);
indent_level = indent_level + 1;
this.write(foo);
indent_level = indent_level - 1;
}
}
}
An exception arises if I call the method and give an Object that has an array attribute; all attributes until the array are written properly to the output file.
The exception is "java.lang.IllegalArgumentException: Argument is not an array".
In d = Array.get(c, j).getClass(); c is of type java.lang.Class, but an array is expected.
You should change it to d = Array.get(fields_c[i].get(obj), j) and use c#getComponentType for get the type of the array.
This may not be what you're after, but if this is to do with serialisation then I recommend "Simple";
http://simple.sourceforge.net/
It makes Java <=> XML serialisation unbelievably easy.
Why you're passing Class of elements instead of elements:
Object[] array = fields_c[i].get(obj);
for(j = 0; j < Array.getLength(array); j++)
{
Object foo = Array.get(array, j); // not .getClass()
indent_level = indent_level + 1;
this.write(foo);
indent_level = indent_level - 1;
}

Categories

Resources