Create sorted array from unsorted ArrayList - java

I have an ArrayList filled with objects of the class result, each result has an attribute named value. I now want to create an Array which is filled with references to the same memory location as in the ArrayList but now in order where to object with the highest value is in the first location, the second highest in the second location and so forth.
I have searched here but haven't found any other post like it.

There are multiple ways to solve it using Gauava or lambda expressions.
Hope this implementation solve your problem.
package com;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class TestDemo {
public static void main(String[] args) {
List < HockeyPlayer > players = new ArrayList < HockeyPlayer > ();
HockeyPlayer obj1 = new HockeyPlayer();
obj1.goalsScored = 22;
players.add(obj1);
HockeyPlayer obj2 = new HockeyPlayer();
obj2.goalsScored = 11;
players.add(obj2);
HockeyPlayer obj3 = new HockeyPlayer();
obj3.goalsScored = 111;
players.add(obj3);
HockeyPlayer obj4 = new HockeyPlayer();
obj4.goalsScored = 3;
players.add(obj4);
Collections.sort(players, new Comparator < HockeyPlayer > () {
#Override public int compare(HockeyPlayer player1, HockeyPlayer player2) {
return player1.goalsScored - player2.goalsScored;
}
});
for (int i = 0; i < players.size(); i++) {
System.out.println(players.get(i).goalsScored);
}
HockeyPlayer array[] = new HockeyPlayer[players.size()];
players.toArray(array); // contains reference
for (int i = 0; i < array.length; i++) {
System.out.println(array[i].goalsScored);
}
}
}
class HockeyPlayer {
public int goalsScored;
}

Related

Java Client Server with RMI

Write a Java client-server program applying RMI. The client program generate two arrays of type class Integer. The client calls method that is on the server side in a remote object. The server put these two arrays into one array, sort the array and returns the sorted array to the client. The client displays the sorted array on the console. Use the following interface. Do not change it.
import java.util.ArrayList;
import java.rmi.*;
public interface MergeInterface extends Remote {
public ArrayList mergeAndSort(ArrayList a, ArrayList b) throws RemoteException;
}
The following sequential program is putting two arrays together, sorting array and display:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> a = new ArrayList<Integer>();
ArrayList<Integer> b = new ArrayList<Integer>();
Random r = new Random();
int m = r.nextInt(900) + 100;
for (int i = 0; i < m; i++) {
a.add(r.nextInt(500) + 10);
}
int n = r.nextInt(900) + 100;
for (int i = 0; i < n; i++) {
b.add(r.nextInt(500) + 10);
}
a.addAll(b);
Collections.sort(a);
for (Integer i : a) {
System.out.println(i);
}
}
}
This is how to implement an interface on a class. I would also consider creating a generic class for this or strongly typing the ArrayLists, but that requires a change to the interface.
public interface MergeInterface extends Remote {
public ArrayList mergeAndSort(ArrayList a, ArrayList b) throws RemoteException;
}
public static void main(String[] args) {
ArrayList a = new ArrayList();
ArrayList b = new ArrayList();
Random r = new Random();
int m = r.nextInt(900) + 100;
for (int i = 0; i < m; i++) {
a.add(r.nextInt(500) + 10);
}
int n = r.nextInt(900) + 100;
for (int i = 0; i < n; i++) {
b.add(r.nextInt(500) + 10);
}
for (Integer i : (ArrayList<Integer>)new MergeImpl().mergeAndSort(a, b)) {
System.out.println(i);
}
}
public static class MergeImpl implements MergeInterface {
#Override
public ArrayList mergeAndSort(ArrayList a,
ArrayList b) {
ArrayList merged = new ArrayList();
merged.addAll(a);
merged.addAll(b);
Collections.sort(merged);
return merged;
}
}

Java identifying generic container element type

What I am trying to achieve is a map of generic lists that I can then serialize. I have achieved this but probably not in the best way, anyway I don't understand one point which I describe further below.
Basically I don't see how mClass ends up being "[Ljava.lang.Integer" i.e. Integer[] and not only "java.lang.Integer".
Edit: In order to make my question clear. I don't understand why mClass is Integer[] when I instantiated the class with GenericArrayData< Integer>, i.e. I was expecting Integer. Thanks
import java.util.HashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import junit.framework.Assert;
import org.junit.Test;
public class TestDataCollectorTest {
public class GenericArrayData<T> {
public Class mClass;
public CopyOnWriteArrayList<T[]> data;
public GenericArrayData(Class<T> type) {
mClass = type;
data = new CopyOnWriteArrayList<>();
}
}
public <T> void logGenericArrayData(HashMap<String, GenericArrayData> map, String tag, T[] obj) {
if (map.containsKey(tag)) {
GenericArrayData<T> d = map.get(tag);
d.data.add(obj);
return;
}
System.out.println("Adding log entry named\"" + tag + "\"");
Class k = obj.getClass();
GenericArrayData<T> d = new GenericArrayData<T>(k);
d.data.add(obj);
map.put(tag, d);
}
#Test
public void basics() {
HashMap<String, GenericArrayData> map = new HashMap<>();
GenericArrayData<Integer> list = new GenericArrayData<>(Integer.class);
Integer[][] inputData = new Integer[10][10];
for (int i = 0; i < inputData.length; ++i) {
inputData[i] = new Integer[10];
for (int j = 0; j < inputData[0].length; ++j) {
inputData[i][j] = i * 100 + j;
}
logGenericArrayData(map, "integers", inputData[i]);
}
Assert.assertEquals(1, map.size());
GenericArrayData d = map.get("integers");
Assert.assertEquals(10, d.data.size());
System.out.println(d.mClass);
Integer[] ia = new Integer[0];
System.out.println(ia.getClass());
Assert.assertTrue(ia.getClass() == d.mClass); // I don't quite understand
Integer[][] outputData = new Integer[d.data.size()][];
outputData = (Integer[][]) d.data.toArray(outputData);
Assert.assertEquals(inputData.length, outputData.length);
for (int i = 0; i < inputData.length; ++i) {
Assert.assertEquals(inputData[i], outputData[i]);
}
}
}

Casting from ArrayList<Object> to my own class

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.

Adding Multiple Values in ArrayList at a single index

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.

Overrided add isn't working

Add is supposed to be an overrided method in which the string is put in the arraylist in alphabetical order, but whenever I execute the program, the Arraylist is always in the order that I added it in.
Here's Test:
import java.util.*;
public class Test
{
private static ArrayList x=new ArrayList();
private static ArrayList<String> li=new ArrayList<String>();
private static SortedList s=new SortedList();
// private static Person p[]=new Person[4];
// private static Fraction f[]=new Fraction[5];
public static void main(String args[])
{
//number 1
x.add(5);
x.add(6);
x.add(1.5);
x.add(7);
x.add(2.5);
System.out.println(average(x,2)); //5.5
System.out.println(average(x,7)); //4.4
//number 2
li.add("Hi");
li.add("del");
li.add("there");
li.add("del");
li.add("you");
li.add("del");
System.out.println(li);
takeOut(li,"del");
System.out.println(li);
//number 3
s.add("dog");
s.add("anteater");
s.add("kewl");
s.add("kitty");
s.add("a");
System.out.println(s);
//number 4
// p[0]=new Person("Kremer","Jim");
//p[1]=new Person("Shi","Kevin");
// p[2]=new Person("Shi","Rebecca"); //I know I spelled your name wrong, Rebecca. (I needed two last names to be the same)
// p[3]=new Person("Herman", "Jimmy");
// Arrays.sort(p); //static method in java.util.Arrays
// for(int i=0; i<p.length; i++)
System.out.println(p[i].getFirstName()+" "+p[i].getLastName());
//number 5
f[0]=new Fraction(4,5);
f[1]=new Fraction(5,4);
f[2]=new Fraction(-8,3);
f[3]=new Fraction(6,5);
f[4]=new Fraction(-1,2);
Arrays.sort(f);
for(int i=0; i<f.length; i++)
System.out.println(f[i].getNum()+"/"+f[i].getDenom());
}
//number 1
public static Double average(ArrayList samples, int num)
{
double sum=0.0;
if(num>samples.size())
{
for(int i=0; i<samples.size(); i++)
{
if(samples.get(i) instanceof Integer)
sum+=(Integer)samples.get(i);
else
sum+=(Double)samples.get(i);
}
return sum/samples.size();
}
else
{
for(int i=0; i<num; i++)
{
if(samples.get(i) instanceof Integer)
sum+=(Integer)samples.get(i);
else
sum+=(Double)samples.get(i);
}
return sum/num;
}
}
//number 2
public static void takeOut(List<String> words, String del)
{
for(int i=0; i<words.size(); i++)
{
if(words.get(i).equals(del))
{
words.remove(i);
i--;
}
}
}
}
And here's SortedList:
import java.util.ArrayList;
import java.util.List;
import java.lang.String;
public class SortedList extends ArrayList<String>
{
private ArrayList<String> a;
public SortedList()
{
a = new ArrayList<String>(10);
}
public SortedList(int cap)
{
super(cap);
}
public boolean add(String x)
{
if(a.size()!=0)
{
for(int i=0; i<a.size(); i++)
{
if(i==a.size()-1)
if(x.compareTo(a.get(i))>=0)
super.add(x);
else
{
if(i==0)
if(x.compareTo(a.get(i))<=0)
super.add(0,x);
if(x.compareTo(a.get(i))>=0 && x.compareTo(a.get(i+1))<=0)
super.add(i+1,x);
}
}
}
else
super.add(x);
return true;
}
}
Thanks in advance!
a.size() != 0 is always false as your SortedList implementation doesn't add any elements in the list a. This results that super.add(x) is always used and the overridden add-method doesn't actually modify the behavior of an ArrayList
User,
Look up Java Collections interface. Java can sort these elements alphabetically for you:
ArrayList<String> a = new ArrayList<String>
a.add("world");
a.add("hello");
Collections.sort(a);
//sorted alphabetically now
If the default sort is the wrong direction, just implement your own Comparator and call:
Collections.sort(a, myComparator);
This should do what you are seeking, unless of course this is a homework assignment...

Categories