I have a method that receives an array of strings and I need to create objects with appropriate names.
For example:
public class temp {
public static void main(String[] args){
String[] a=new String[3];
a[0]="first";
a[1]="second";
a[2]="third";
createObjects(a);
}
public static void createObjects(String[] s)
{
//I want to have integers with same names
int s[0],s[1],s[2];
}
}
If I receive ("one","two") I must create:
Object one;
Object two;
If I receive ("boy","girl") I must create:
Object boy;
Object girl;
Any help would be appreciated.
Can't do that in java. You can instead create a Map who's keys are the strings and the values are the objects.
First create Map which contains the key as String representation of Integers.
public class Temp {
static Map<String, Integer> lMap;
static {
lMap = new HashMap<String, Integer>();
lMap.put("first", 1);
lMap.put("second", 2);
lMap.put("third", 3);
}
public static void main(String[] args) {
Map<String, Integer> lMap = new HashMap<String, Integer>();
String[] a = new String[3];
a[0] = "first";
a[1] = "second";
a[2] = "third";
Integer[] iArray=createObjects(a);
for(Integer i:iArray){
System.out.println(i);
}
}
public static Integer[] createObjects(String[] s) {
// I want to have integers with same names
Integer[] number = new Integer[s.length];
for (int i = 0; i < s.length; i++) {
number[i] = lMap.get(s[i]);
}
return number;
}
}
Related
public class MergeNames {
public static void main(String[] args) {
String[] names1 = new String[] { "Ava", "Emma", "Olivia" };
String[] names2 = new String[] { "Olivia", "Sophia", "Emma" };
int na1 = names1.length;
int na2 = names2.length;
String [] result = new String[na1 + na2];
System.arraycopy(names1, 0, result, 0, na1);
System.arraycopy(names2, 0, result, na1, na2);
System.out.println(Arrays.toString(result));
}
}
I created Two Array Object String and Assign Same String values. After need to merge the two String array object into another String array Object.
Note: Without no duplication
I want output like
["Ava", "Emma", "Olivia", "Sophia", "Emma"]
You can use Java Stream API the Stream.of(). See the example for better understanding.
Reference Code
public class Main {
public static <T> Object[] mergeArray(T[] arr1, T[] arr2)
{
return Stream.of(arr1, arr2).flatMap(Stream::of).distinct().toArray();
}
public static void main(String[] args) {
String[] names1 = new String[] { "Ava", "Emma", "Olivia" };
String[] names2 = new String[] { "Olivia", "Sophia", "Emma" };
Object [] result = mergeArray(names1, names2);
System.out.println(Arrays.toString(result));
}
}
Output
[Ava, Emma, Olivia, Sophia]
You have small mistake
String [] result = new String[na1 + na2];
not int
I have two ArrayLists, teamList1 and teamList2, which each contain five Team objects. I'm comparing those contents to each other in one of my methods. I must pass in these two ArrayLists as a single 2-element simple array argument, Objects[], into the method. I'm getting a compiler error because I'm struggling with casting from type Objects into type Team. In other words, changing from a Collection to a simple array back to a Collection is giving me an error. Anyone have a tip on my casting error?
CommonElements.java
package test;
import javax.swing.*;
import java.util.*;
public class CommonElements {
List<Comparable> teamList1 = new ArrayList<Comparable>();
List<Comparable> teamList2 = new ArrayList<Comparable>();
List<Comparable> commonList = new ArrayList<Comparable>();
Object[] listCollection = new Object[2];
int comparisonCount;
public static void main(String[] args) {
new CommonElements();
}
public CommonElements() {
comparisonCount = 0;
Team a = new Team("Boston");
Team b = new Team("Seattle");
Team c = new Team("Newark");
Team d = new Team("Houston");
Team e = new Team("Salt Lske City");
teamList1.add(a);
teamList1.add(b);
teamList1.add(c);
teamList1.add(d);
teamList1.add(e);
Team f = new Team("Seattle");
Team g = new Team("Nashville");
Team h = new Team("St. Louis");
Team i = new Team("New York");
Team j = new Team("Boston");
teamList2.add(f);
teamList2.add(g);
teamList2.add(h);
teamList2.add(i);
teamList2.add(j);
listCollection[0] = teamList1;
listCollection[1] = teamList2;
findCommonElements(listCollection);
System.out.println(comparisonCount);
}
public Comparable[] findCommonElements(Object[] collections)
{
ArrayList<Object> objectTeam1 = new ArrayList<Object>(Arrays.asList(collections[0]));
ArrayList<Object> objectTeam2 = new ArrayList<Object>(Arrays.asList(collections[1]));
ArrayList<Team> team1 = (ArrayList)objectTeam1;
ArrayList<Team> team2 = (ArrayList)objectTeam2;
Team[] commonList = new Team[5];
int i = 0;
for(Team x:team1)
{
for(Team y:team2)
{
comparisonCount++;
if(x.compareTo(y) == 0)
{
commonList[i] = x;
System.out.println(commonList[i].teamName);
i++;
break; /*to ensure it looks for only one match per entry*/
}
}
}
return commonList;
}
public int getComparisons()
{
return comparisonCount;
}
}
Team.java
package test;
public class Team implements Comparable<Team> {
String teamName = new String();
public void setName ( String n ) {
teamName = n;
}
public Team(String n) {
setName(n);
}
public int compareTo(Team x)
{
if(this.teamName.equals(x.teamName))
{
return 0;
}
else
{
return -1;
}
}
}
That is a very unfortunate and odd way of passing the arguments, but anyway, to make it work, you can do:
#SuppressWarnings("unchecked")
ArrayList<Team> team1 = (ArrayList<Team>)collections[0];
#SuppressWarnings("unchecked")
ArrayList<Team> team2 = (ArrayList<Team>)collections[1];
Your existing code was taking each ArrayList, putting it into a one element array, wrapping that array as a list, creating an ArrayList from it, and trying to view the ArrayList<ArrayList<Team>> as an ArrayList<Team>.
A few other things I see... you don't need to assign these to variables if you're only using them to add to the list:
Team a = new Team("Boston");
...
teamList1.add(a);
You can simply do:
teamList1.add(new Team("Boston"));
You don't need to create the listCollection array separately, because you can create it inline when passing the arguments:
findCommonElements(new Object[] { teamList1, teamList2 });
In your Team class, this:
String teamName = new String();
Should simply be:
String teamName;
In your compareTo method:
public int compareTo(Team x)
{
if(this.teamName.equals(x.teamName))
{
return 0;
}
else
{
return -1;
}
}
That should be:
public int compareTo(Team x)
{
return teamName.compareTo(x.teamName);
}
which is shorter, and honors the compareTo requirement that sgn(x.compareTo(y)) == -sgn(y.compareTo(x)) for all x and y.
I am working on a program where I have to count the frequency of food items in a file in order to sort them in descending order.
For example: if my file has ( pizza, ice_cream, pasta, pizza )
I want my program to print something similar to this:
1 ice_cream
1 pasta
2 pizza
I am using a bubble sort algorithm but it seems that I am missing something for this algorithm to work. Any help will be greatly appreciated!
Within class Listabc, I have two local variables and a method called "compareTo."
class Listabc {
int count = 1;
String item;
int compareTo(Listabc listabc) {
return 0;
}
}
Within my main method, I have a bubble sort algorithm to sort the food items in a descending order
public class MainMethod {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new BufferedReader(new FileReader("file.txt")));
List<Listabc> lists = new ArrayList<Listabc>();
for (int a = 0; a < lists.size() - 1; ++a) {
for (int b = a + 1; b < lists.size(); b++) {
if ((lists.get(b)).compareTo(lists.get(a)) > 0) {
Listabc temp = lists.get(a);
lists.set(a, lists.get(b));
lists.set(b, temp);
}
}
System.out.println(lists.get(a));
}
}
}
Your implementation of compareTo method is broken. You need to change it by applying a real comparison:
int compareTo(Listabc listabc) {
return 0; //this means every element is "similar" to another
}
Here's an example about comparing the elements by the item field:
int compareTo(Listabc listabc) {
return this.item.compareTo(listabc.item);
}
If you make Listabc implement comparable you can just call Collections.sort(lists)
Below program will sort the list using Collections.sort
public class SortMap {
public static void main(String[] args) {
Map<String, Integer> t = new HashMap<String, Integer>();
Scanner sc = null;
try {
sc = new Scanner(new File("foodlist.txt"));
while (sc.hasNext()) {
String item = sc.next();
if (t.get(item) != null) {
Integer count = t.get(item);
t.put(item,++count);
} else {
t.put(item, 1);
}
}
Set<Map.Entry<String, Integer>> mp = t.entrySet();
List<Map.Entry<String, Integer>> ll = new ArrayList<Map.Entry<String,Integer>>(mp);
Collections.sort(ll, new SortMap.ValueComparator());
System.out.println(ll);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
sc.close();
}
}
static class ValueComparator implements Comparator<Map.Entry<String, Integer>> {
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
return o1.getValue().compareTo(o2.getValue());
}
}
}
I am trying to insert the values to hash map through object, and i want to check if the values are inserted in to hash map. so i am using this code but in runtime i am not able to get any output.
How to resolve this?
Code:
import java.util.*;
import java.io.*;
import java.lang.*;
public class TaskList
{
private static HashMap<Integer, Object[]> dataz = new HashMap<Integer,Object[]>();
private static HashMap<Integer, Object[]> screen_dataz = new HashMap<Integer,Object[]>();
public final static Object[][] longValues = {{"10", "kstc-proc", "10.10.10.10.10.","5","O"},{"11", "proc-lvk1", "12.1.2.","4","O"},{"13", "trng-lvk1", "4.6.1.","3","O"}};
private static String sl,pid,tid,mval,status;
public static void main(String args[])
{
addTask();
}
public static void addTask()
{
for (int k=0; k<longValues.length; k++)
{
screen_dataz.put(k,longValues);
}
Set mapSet = (Set) screen_dataz.entrySet();
Iterator mapIterator = mapSet.iterator();
while (mapIterator.hasNext())
{
Map.Entry mapEntry = (Map.Entry) mapIterator.next();
String keyValue = (String) mapEntry.getKey();
String value = (String) mapEntry.getValue();
System.out.println(value);
}
}
}
First, you must add a row of the longValues matrix to the map, and not the whole matrix:
for (int k=0; k<longValues.length; k++)
{
screen_dataz.put(k,longValues[k]);
}
Then, while iterating extract the value as Object[] and not String, and key as Integer
while (mapIterator.hasNext())
{
Map.Entry mapEntry = (Map.Entry) mapIterator.next();
Integer keyValue = (Integer) mapEntry.getKey();
Object[] value = (Object[]) mapEntry.getValue();
//iterate over the array and print each value
for (int i=0; i<value.length; i++) {
System.out.print(value[i] + " ");
}
System.out.println();
}
Your code with a few fixes/improvements:
do not use casting when using generics
the loop adding elements to screen_dataz was always adding the same object
the value stored in the map is an array which means it will not be printed as you expect with a simple call to toString()
public class TaskList {
private static HashMap<Integer, String[]> dataz = new HashMap<Integer, String[]>();
private static HashMap<Integer, String[]> screen_dataz = new HashMap<Integer, String[]>();
public final static String[][] longValues = {
{ "10", "kstc-proc", "10.10.10.10.10.", "5", "O" },
{ "11", "proc-lvk1", "12.1.2.", "4", "O" },
{ "13", "trng-lvk1", "4.6.1.", "3", "O" } };
private static String sl, pid, tid, mval, status;
public static void main(String args[]) {
addTask();
}
public static void addTask() {
for (int k = 0; k < longValues.length; k++) {
screen_dataz.put(k, longValues[k]);
}
Set<Entry<Integer, String[]>> mapSet = screen_dataz.entrySet();
Iterator<Entry<Integer, String[]>> mapIterator = mapSet.iterator();
while (mapIterator.hasNext()) {
Entry<Integer, String[]> mapEntry = mapIterator.next();
Integer keyValue = mapEntry.getKey();
String[] value = mapEntry.getValue();
System.out.println(Arrays.toString(value));
}
}
}
One correction in your code:
You may want to update your for loop
as
for (int k=0; k<longValues.length; k++)
{
screen_dataz.put(k,longValues[k]);
}
First, change your for loop to populate to screen_dataz like this.
for (int k=0; k<longValues.length; k++)
{
screen_dataz.put(k,longValues[k]);
}
Next, make the below change:-
String keyValue = mapEntry.getKey().toString();
String value = Arrays.asList((Object[])mapEntry.getValue()).toString();
This will print your value properly.
Quite a few things to comment about this code.
First, the generic arguments of the parameterized type are incorrect. The map is currently storing Map<Long,Object[]> however objects of type Object[][] are added to the Map. I assume you want to enter each Object[] as a separate Entry in the Map.
for (int k=0; k<longValues.length; k++)
{
screen_dataz.put(k,longValues[k]);
}
The second piece to look at is the iteration over the Map entries. Instead of using the Iterator use a for..each loop.
for(Entry<Integer,Object[]> entry: screen_dataz.entrySet()){
//repetitive task
}
Final Output
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class TaskList
{
private static HashMap<Integer, Object[]> dataz = new HashMap<Integer,Object[]>();
private static HashMap<Integer, Object[]> screen_dataz = new HashMap<Integer,Object[]>();
public final static Object[][] longValues = {{"10", "kstc-proc", "10.10.10.10.10.","5","O"},{"11", "proc-lvk1", "12.1.2.","4","O"},{"13", "trng-lvk1", "4.6.1.","3","O"}};
private static String sl,pid,tid,mval,status;
public static void main(String args[])
{
addTask();
}
public static void addTask()
{
for (int k=0; k<longValues.length; k++)
{
screen_dataz.put(k,longValues[k]);
}
for(Entry<Integer,Object[]> entry: screen_dataz.entrySet()){
System.out.println(entry.getKey());
for(Object obj: entry.getValue()){
System.out.println(obj.toString());
}
}
}
}
I think using screen_dataz.put(k,longValues[k]); in a loop will help you.
You could also use an Iterator for this.
I have a double ArrayList in java like this.
List<double[]> values = new ArrayList<double[]>(2);
Now what I want to do is to add 5 values in zero index of list and 5 values in index one through looping.
The zeroth index would have values {100,100,100,100,100}
The index 1 would have values {50,35,25,45,65}
and all of these values are stored in a double array in following order
double[] values = {100,50,100,35,100,25,100,45,100,65}
How can i do it?
#Ahamed has a point, but if you're insisting on using lists so you can have three arraylist like this:
ArrayList<Integer> first = new ArrayList<Integer>(Arrays.AsList(100,100,100,100,100));
ArrayList<Integer> second = new ArrayList<Integer>(Arrays.AsList(50,35,25,45,65));
ArrayList<Integer> third = new ArrayList<Integer>();
for(int i = 0; i < first.size(); i++) {
third.add(first.get(i));
third.add(second.get(i));
}
Edit:
If you have those values on your list that below:
List<double[]> values = new ArrayList<double[]>(2);
what you want to do is combine them, right? You can try something like this:
(I assume that both array are same sized, otherwise you need to use two for statement)
ArrayList<Double> yourArray = new ArrayList<Double>();
for(int i = 0; i < values.get(0).length; i++) {
yourArray.add(values.get(0)[i]);
yourArray.add(values.get(1)[i]);
}
How about
First adding your desired result as arraylist and
and convert to double array as you want.
Try like this..
import java.util.ArrayList;
import java.util.List;
public class ArrayTest {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
// Your Prepared data.
List<double[]> values = new ArrayList<double[]>(2);
double[] element1 = new double[] { 100, 100, 100, 100, 100 };
double[] element2 = new double[] { 50, 35, 25, 45, 65 };
values.add(element1);
values.add(element2);
// Add the result to arraylist.
List<Double> temp = new ArrayList<Double>();
for(int j=0;j<values.size(); j++) {
for (int i = 0; i < values.get(0).length; i++) {
temp.add(values.get(0)[i]);
temp.add(values.get(1)[i]);
}
}
// Convert arraylist to int[].
Double[] result = temp.toArray(new Double[temp.size()]);
double[] finalResult = new double[result.length]; // This hold final result.
for (int i = 0; i < result.length; i++) {
finalResult[i] = result[i].doubleValue();
}
for (int i = 0; i < finalResult.length; i++) {
System.out.println(finalResult[i]);
}
}
}
ArrayList<ArrayList> arrObjList = new ArrayList<ArrayList>();
ArrayList<Double> arrObjInner1= new ArrayList<Double>();
arrObjInner1.add(100);
arrObjInner1.add(100);
arrObjInner1.add(100);
arrObjInner1.add(100);
arrObjList.add(arrObjInner1);
You can have as many ArrayList inside the arrObjList. I hope this will help you.
create simple method to do that for you:
public void addMulti(String[] strings,List list){
for (int i = 0; i < strings.length; i++) {
list.add(strings[i]);
}
}
Then you can create
String[] wrong ={"1","2","3","4","5","6"};
and add it with this method to your list.
Use two dimensional array instead. For instance, int values[][] = new int[2][5]; Arrays are faster, when you are not manipulating much.
import java.util.*;
public class HelloWorld{
public static void main(String []args){
List<String> threadSafeList = new ArrayList<String>();
threadSafeList.add("A");
threadSafeList.add("D");
threadSafeList.add("F");
Set<String> threadSafeList1 = new TreeSet<String>();
threadSafeList1.add("B");
threadSafeList1.add("C");
threadSafeList1.add("E");
threadSafeList1.addAll(threadSafeList);
List mainList = new ArrayList();
mainList.addAll(Arrays.asList(threadSafeList1));
Iterator<String> mainList1 = mainList.iterator();
while(mainList1.hasNext()){
System.out.printf("total : %s %n", mainList1.next());
}
}
}
You can pass an object which is refering to all the values at a particular index.
import java.util.ArrayList;
public class HelloWorld{
public static void main(String []args){
ArrayList<connect> a=new ArrayList<connect>();
a.add(new connect(100,100,100,100,100));
System.out.println(a.get(0).p1);
System.out.println(a.get(0).p2);
System.out.println(a.get(0).p3);
}
}
class connect
{
int p1,p2,p3,p4,p5;
connect(int a,int b,int c,int d,int e)
{
this.p1=a;
this.p2=b;
this.p3=c;
this.p4=d;
this.p5=e;
}
}
Later to get a particular value at a specific index, you can do this:
a.get(0).p1;
a.get(0).p2;
a.get(0).p3;.............
and so on.