Java LinkedList obtaining first element - java

I have an Java LinkedList which stores two values (code below).
I was wondering how i can obtain the first value only?
I have:
LinkedList list = new LinkedList();
list.add(number+" "+string);
I want to be able to just print out number from the list. Is it possible?

First of all, note that by doing list.add(number + " " + string) you're adding a single object, namely the string formed by concatenating number and string.
That said, you could try something like this, to get the first part of the first element:
list.get(0).split(" ")[0]
Example:
int number = 17;
String string = "hello";
LinkedList<String> list = new LinkedList<String>();
list.add(number+" "+string);
// Print number of first item:
System.out.println(list.get(0).split(" ")[0]); // prints "17"

I think you mean the number only.
First get the object at index 0:
String node = list.get(0);
Then extract the first part by looking for the space
String num = node.substring(0,node.indexOf(' '));
Although I suggest looking into HashMaps for such implementation, which takes Key,Value pairs:
For your example, you will need something like:
Map<Long,String> myMap = new HashMap<Long,String>();
myMap.put(number,string);

I'd suggest encapsulating your number and string into a class, like this.
public final class Pojo {
private final Number number;
private final String string;
public Pojo(Number number, String string) {
this.string = string;
this.number = number;
}
public void getNumber() {
return number;
}
public void getString() {
return string;
}
#Override
public String toString() {
return number + " " + string;
}
}
Then, create your List like this:
List<Pojo> list = new LinkedList<Pojo>(); // use generics for compile-time type safety
list.add(new Pojo(42, "Answer to the Ultimate Question of Life, the Universe, and Everything"); // add a Pojo
System.out.println(list.get(0).getNumber());

The List does not store two values. It stores one Object, the String created by concatenating number with a space and the String.
If you want to access individual Objects, you should either use a Map instead of a List or create a custom Object that holds number and string:
a)
Map<Integer, String> map = new Hashmap<Integer, String>();
map.put(number, string);
b)
public class MyObject{
private Number number;
private String string;
// + getters and setters
}
Also:
a) you should not use Non-generic Collections anymore. Generics were introduced 7 years ago, there should not be any reason not to use them these days.
So you should use this:
LinkedList<String> list = new LinkedList<String>();
Or this:
LinkedList<MyCustomObject> list = new LinkedList<MyCustomObject>();
b) are you sure you want a LinkedList? In most cases, ArrayList is the general purpose List implementation. LinkedList performs better if you have many add() statements and don't know in advance how large your List will be, but ArrayList performs a lot better for random access.

You are adding a string to that list. x + y, where either x or y is a string produces a string. If you want to have access to the number and the string, you should consider using another type - not a String here. Something like:
LinkedList<Pair<Number, String>> list = new LinkedList<Pair<Number, String>();
list.add(new Pair<Number, String>(number, string));
This way, to obtain the number, stored in the first element of the list:
Pair thePair = list.get(0);
number = (Number)thePair.left;
Pair is a class, you can find in Apache Commons:
http://commons.apache.org/lang/api-3.0-beta/org/apache/commons/lang3/Pair.html
(A source for many useful Java classes)

number+" "+string
Acts as a single string, if you want to get the number:
list.get(index).split(" ")[0]
Even if it works, this is not a clear way to manage a pair of values.
From an object-oriented point of view (and this is the right context :D ), use directly an object:
class Pair {
int number;
String str;
}
Put your object to the list:
Pair pair = new Pair();
pair.number = 1;
pair.str = "hello";
list.add(pair);
And get your number:
((Pair)list.get(0)).number;
Of course you can use class methods and generics to manage all in a better way.

when you are initiating a Linkedlist in java, you should specify the data type that you are going to store in. You haven't done so. As your requirement it should be:
LinkedList<int> list=new LinkedList<>();
After that you can add your elements:
list.add(<number>);
Then you can get the first element:
list.getFirst();
Then you can print that.

Related

How to sort List<String> list numerically?

I have a List<String> list which is initialized to an arrayList. That is,
List<String>list = new ArrayList();
It has the following elements.
[1,bread, 1,turkey, 10,potato, 11,plum, 12,carrot, 2,milk, 2,rice]
I would like to sort the list so that the numbers are in ascending order. For example,
[1,bread,1 turkey,2,milk,2,rice,10,potato,11,plum,12,carrot]
How can I do that?
Java is an Object-Oriented language, and you should use it.
So, create a new class with two fields: int and String.
Now parse your strings and create objects, i.e. 1,bread is parsed into the int value 1, and the String value bread.
Next, make your class implement Comparable, and implement the compareTo method to order the objects by the int value.
Finally, now that List<String> was converted to List<MyObj>, call Collections.sort(list).
You're not trying to sort the elements in the List--you're trying to sort pairs of elements. You can't do that with a simple sort. What you'll need to do is:
Define a class with two fields, an int and a String. Make the class implement Comparable.
Define a comparator for the class that compares the int fields to get the order you want. You'll have to decide what your comparator will do if the int fields are equal (do you want the String fields to be in ascending order?)
Create a List<YourClass> whose size is half the size of the original list, by going through the source list in pairs, something like
for (int i = 0; i < list.size() - 1; i += 2) {
create a YourClass by converting list.get(i) to an int, and using list.get(i+1) as the String field
}
Sort the new list
If desired, recreate a List<String> by going through the List<YourClass> and adding a String conversion of the int, followed by the String field from YourClass, to the new list.
I don't know what you're planning to do with the String list, but in most cases it will make your program easier if you create a List<YourClass> list as soon as possible, and work with YourClass objects throughout the rest of the program
The simple answer is that you could provide a custom Comparator which understands the structure of each individual String element and can parse and compare them properly. Something like this:
#Test
public void testShouldSortByNumber() {
// Arrange
List<String> list = Arrays.asList("1,bread", "1,turkey", "10,potato", "11,plum", "12,carrot", "2,milk", "2,rice");
final List<String> EXPECTED_LIST = Arrays.asList("1,bread", "1,turkey", "2,milk", "2,rice", "10,potato", "11,plum", "12,carrot");
// Act
Collections.sort(list, new Comparator<String>() {
#Override
public int compare(String o1, String o2) {
try {
int i1 = Integer.parseInt(o1.split(",")[0]);
int i2 = Integer.parseInt(o2.split(",")[0]);
// If the numbers are equal, could order by alpha on the second part of the string split
return i1 < i2 ? -1 : i1 == i2 ? 0 : 1;
} catch (Exception e) {
// Lots of possible errors above -- NPE, NFE, invalid string format, etc.
e.printStackTrace();
}
return 0;
}
});
// Assert
assert list.equals(EXPECTED_LIST);
}
The more complex answer is that you should better define your problem -- what should the result be if an element is empty or null, if the numbers are equal are the other strings compared lexicographically or is it irrelevant?
You may also want to use a different data structure -- if the content of each element is really two different logical concepts, a tuple or class may be correct. Or, you may want to use a SortedMap (of which TreeMap is probably the best implementation here) where the key is the "ingredient" and the value is the "count" (or "cost", I don't have any context on the numerical value).
You can also enhance the code above with a lambda if you have access to JDK 8+.

How to remove the brackets [ ] from ArrayList#toString()?

I have created an Array List in Java that looks something like this:
public static ArrayList<Integer> error = new ArrayList<>();
for (int x= 1; x<10; x++)
{
errors.add(x);
}
When I print errors I get it errors as
[1,2,3,4,5,6,7,8,9]
Now I want to remove the brackets([ ]) from this array list. I thought I could use the method errors.remove("["), but then I discovered that it is just boolean and displays a true or false. Could somebody suggest how can I achieve this?
Thank you in advance for your help.
You are probably calling System.out.println to print the list. The JavaDoc says:
This method calls at first String.valueOf(x) to get the printed object's string value
The brackets are added by the toString implementation of ArrayList. To remove them, you have to first get the String:
String errorDisplay = errors.toString();
and then strip the brackets, something like this:
errorDisplay = errorDisplay.substring(1, errorDisplay.length() - 1);
It is not good practice to depend on a toString() implementation. toString() is intended only to generate a human readable representation for logging or debugging purposes. So it is better to build the String yourself whilst iterating:
List<Integer> errors = new ArrayList<>();
StringBuilder sb = new StringBuilder();
for (int x = 1; x<10; x++) {
errors.add(x);
sb.append(x).append(",");
}
sb.setLength(sb.length() - 1);
String errorDisplay = sb.toString();
Note that this is not an array, just a String displaying the contents of the list. To create an array from a list you can use list.toArray():
// create a new array with the same size as the list
Integer[] errorsArray = new Integer[errors.size()];
// fill the array
errors.toArray(errorsArray );
EDIT: From an object-oriented perspective one could argue that errors and errorsDisplay conceptually belong together in a class, e.g:
public class Errors {
private final List<Integer> codes = new ArrayList<>();
public void add(int error) {
codes.add(error);
}
public Stream<Integer> get() {
return codes.stream();
}
#Override
public String toString() {
return codes.stream()
.map(Object::toString)
.collect(Collectors.joining(", "));
}
}
Short answer: System.out.println(errors.toString().substring(1, errors.toString().length() - 1))
Explanation: when you call System.out.println(obj) with an Object as a parameter, the printed text will be the result of obj.toString(). ArrayList.toString() is implemented in a way that makes it represent its content between brackets [] in a comma separated concatenation of each of the contained items (their .toString() representation as well).
It is not a good practice to rely on another class's toString() implementation. You should use your own way to format your result.
The brackets you see are just an automatic way to display a List in JAVA (when using System.out.println(list); for example.
If you do not want them to show when showing it, you can create a custom method :
public void showList(List<Integer> listInt)
{
for(int el : listInt)
{
System.out.print(el + ", ");
}
}
Then adjust this code to show this according to your liking !
The brackets are not actually within the list it's just a representation of the list. If any object goes into a String output the objects toString() method gets called. In case of ArrayList this method delivers the content of the list wrapped by this brackets.
If you want to print your ArrayList without brackets just iterate over it and print it.
There are not brackets inside your list.
This is just the way Java prints a list by default.
If you want to print the content of your list, you can something like this
for (Integer error : errors) {
System.out.format("%d ", error);
}
If you print your error list, it will internally call the toString() method of your list and this method add the brackets. There are a few possibilities. You can get the String via toString() method an remove the brackets from the String. Or you write your own method to print the List.
public static <T> void printList(List<T> list)
{
StringBuilder output = new StringBuilder();
for(T element : list)
output.append(element + ", ");
System.out.println(output);
}
String text = errors.toString().replace("[", "").replace("]", "");//remove brackets([) convert it to string
brackets is not a part of your array list, since as you've mentioned it's Integer typed
ArrayList<Integer>
when you print errors using
System.out.println(errors);
it's just formatting your data, just iterate over the array and print each value separately
System.out.println(error.toString().substring(1, error.toString().length()-1));
This worked for me
For that, you can use String.join method like below.
String.join(",",errors);
This is an ArrayList of Integer. This ArrayList can not contain a character like '['. But you can remove an Integer from it like this -
error.remove(3);
You can write like this.
String output = errors.toString().replaceAll("(^\\[|\\]$)", "");
You can simply remove all the brackets using replaceAll() method like this:-
System.out.println(errors.toString().replaceAll("[\\[\\]]", ""));
I was experimenting with ArrayList and I also wanted to remove the Square brackets after printing the Output and I found out a Solution. I just made a loop to print Array list and used the list method " myList.get(index) " , it works like a charm.
Please refer to my Code & Output below:
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
ArrayList mylist = new ArrayList();
Scanner scan = new Scanner(System.in);
for(int i = 0; i < 5; i++) {
System.out.println("Enter Value " + i + " to add: ");
mylist.add(scan.nextLine());
}
System.out.println("=======================");
for(int j = 0; j < 5; j++) {
System.out.print(mylist.get(j));
}
}
}
OUTPUT
Enter Value 0 to add:
1
Enter Value 1 to add:
2
Enter Value 2 to add:
3
Enter Value 3 to add:
4
Enter Value 4 to add:
5
=======================
12345

Java - arraylist of multidimensional arrays or arraylist of multidimensional arraylists?

I'm learning Java and am trying to wrap my head around these data structures. I'm coming from Python/PHP so I'm used to dynamically sizing arrays on the fly and being able to store multiple data types in one array.
How would I best store this data? Say I don't know how many rows I'll have, but I do know that each row will hold 2 columns of data. One column being a string, and the other column being a double.
Example in pseudo-ish code if I had 3 rows:
array(array("description1", 10.00),
array("description2", 12.00),
array("description3", 14.00));
Then, I want to loop through the array to process the datawith something like:
foreach(rows as row){
myStringVal = row[0]; //on first iteration would be "description1"
myIntVal = row[1]; //on first iteration would be 10.00
... do something with the values ...
}
I'm thinking I need to create an arraylist that holds an array, but I can't store both strings and doubles in a java array, so what do i do? Do I use a map instead, and treat it as if it were an array? For example, do I create a map where the first element is a numeric ID for each row, the second element is the string value, the 3rd element is the double value, and then I use a loop to increase a counter and grab each row from the map that using the numeric ID>
Really confused as to how this will work. Any suggestions? Thanks!
You're not storing "different kind of values", you're storing semantic data that encodes "a tuple" but using the non-java concept of just sticking that in an array. Don't do that, instead use the C/C++/Java concept of encoding linked data as a struct/object:
// our "struct"esque class for the linked data we're handling
class MyObject {
String description;
float value;
Public MyObject(String description, float value) {
this.description = description;
this.value = value;
}
}
// build our list of objects
ArrayList<MyObject> mylist = new ArrayList<MyObject>();
mylist.add(new MyObject("description1", 10));
mylist.add(new MyObject("description2", 12));
mylist.add(new MyObject("description3", 14));
...
// and then we iterate
String d; float v;
for(MyObject m: mylist) {
d = m.description;
v = m.value;
...
}
It looks like a List<Map<String, BigDecimal>> to me.
The List will give you the ability to enter more than one element continuously.
The Map will give you the association between the String and floating-point value, which I've chosen BigDecimal to represent. You could use Double if you wanted.
List<Map<String, BigDecimal>> elements = new ArrayList<>();
elements.add(new HashMap<String, BigDecimal>());
elements.get(0).put("description1", BigDecimal.valueOf("10.00"));
Use a class instead of an array.
public class X
{
private final String description;
private final double value;
public X(final String desc,
final double val)
{
decription = desc;
value = val;
}
// getters
}
If you want to be able to change the description and value then don't make them final.
You could make the description and value variables public, but I would avoid that temptation.

How do I represent a list of strings and a list in Java?

I have data of the form
ith entry = string1, string2....fixed number N of strings,
(name1, name2,....variable number of strings)
i.e. it is a list of (N strings and a list of variable size)
I currently have List<List<String>> and I'm thinking just treat the N+1th to the last string differently...but is there a better way to represent this data? Specifically I'd like to be able to interact with (name1, name2...) as a list rather than as strings
A wrapper like this may be used:
Class MyData
{
private String[] fixedData;
private List<String> variableData;
public MyData(int fixedSizeN) {
fixedData = new String[fixedSizeN];
variableData = new ArrayList<String>();
}
//public get/set go here
}
List<MyData> comboData;
Think in Objects, if a fixed list of strings AND a variable list of strings represent something in your problem domain, wrap both in a class. In this way, you can increase your encapsulation.

How to convert a List of String arrays to a List of objects

I want to convert a List to a List so that each object on my new list includes the first element of each String[].
Do you know if this is possible to do in java?
for example:
public List<String[]> readFile(){
String[]array1={"A","1.3","2.4","2.3"};
String[]array2={"B","1.43","3.4","2.8"};
String[]array3={"C","5.23","2.45","2.9"};
List<String[]>ReadFile= new ArrayList<String[]>();
ReadFile.add(array1);
ReadFile.add(array2);
ReadFile.add(array3);
return ReadFile;
}
Now I want a method which will take the List ReadFile from above to somehow split the arrays of strings into an ID which will be the first element "A", "B", "C" and another part which would be the string array of numbers which I will put through another method to convert numbers from String to type Double. I have already got the method to convert to double but I need to be able to keep track of the ID field because the ID field will be used to identify the array of numbers.
A friend suggested that I create an Object where each objects has one part as a String ID and the other part as an array. That is the part which I do not know how to do.
Can anybody help please?
below is the method declaration which I believe I should have so the return type will be List where each array has been converted to an Object with two parts.
public List<Object> CreateObject(List<String[]>ReadFile){
}
Thanks,
Jetnori.
Hi all, Thank you for taking your time to help.
I can see the benefit of using HashTables. I am as of now trying to implement it. I know i might be sidetracking a little but just to explain what I am trying to do:
In my project I have CSV file with data about gene expression levels. The method that I use from OpenCSV to read the file returns a List(String[]) where each String[] is one row in the file. The first element of each row is variable name (recA, ybjE etc). The rest of the row will be numbers data related to that variable. I want to calculate Pearson's correlation between each of the number arrays. The method which I have got implemented already does that for me but the problem that I have now is that I had to remove the string values from my arrays before I could convert to double by iterating over the array. After I have managed to calculate the correlation between each array of doubles by still keeping the ID linked to the row, I want to be able to draw an undirected node graph between the genes that have a correlation higher than a threshold which I will set (for example correlation higher than 0.80). I don't know if i am biting more than i can chew but I have 30 days to do it and I believe that with the help of people like you guys I will get through it.
Sorry for going on for a bit.
thanks,
Jetnori.
I agree with the answer Alb provided, however this is what your friend has suggested, first you need a class to represent the data. I have included a constructor that parses the data and one that accepts already parsed data, depending on how you like to think of things.
public class NumberList {
private double[] numbers;
private String key;
public NumberList(Strig key, double[] numbers){
this.ley = key;
this.numbers = numbers;
}
public NumberList(String[] inputList) {
key = inputList[0];
numbers = new double[inputList.length-1];
for(int i=1;i<inputList.length;i++){
numers[i-1] = Double.parseDouble(inputList[i]);
}
}
public String getKey() {
return key;
}
public double[] getNumbers() {
return numbers;
}
}
Then you need your function to generate the list:
public List<NumberList> CreateObject(List<String[]> ReadFile){
ArrayList<NumberList> returnList = new ArrayList<NumberList>(ReadFile.size());
for (String[] input : ReadFile) {
returnList.add(new NumberList(input));
}
return returnList;
}
Note this uses the constructor that parses the data, if you use the other constructor then the "CreateObject" function would need to include the parsing logic.
Finally on a side note the standard convention in java is that the only thing that is capitalized are class names and final static fields (which appear in all caps sepearted by underscores), so conventionally the method signature would be:
public List<NumberList> createObject(List<String[]> readFile){
...
}
Sounds like you need a Map instead of a List, it lets you index things by a key (in your case ID).
Map<String, String[]> map = new Hashmap<String, String[]>();
for( String[] array : ReadFile ){
map.put( array[0], array );
}
then to get the array of values for 'A' you would do:
String[] values = map.get( "a" );
If you want the values to be doubles instead of strings you'll want to change the array before putting it (the map.put call) I'd advise using a list or other collections instead of an array also. You also will probably also want to remove the ID part from these values, which my code does not do.
public class Split_ListwithIDs {
Hashtable<String, String[]> table = new Hashtable<String, String[]>();
Splitter spl ;
public Split_ListwithIDs(Splitter split){
spl = split;
}
private void addEntry(String key , String[] vals){
table.put(key, vals);
}
public void parseList(List<String[]> list){
for(String[] entry : list){
String[] temp = new String[entry.length - 1];
System.arraycopy(entry, 1, temp, 0,entry.length - 1);
addEntry(entry[0], spl.GetStringArrayOfNumbers(temp));
}
}
class SplittingHelper implements Splitter{
#Override
public String[] GetStringArrayOfNumbers(String[] arr) {
String[] strArray = null ;
// implementation here
return arr;
}
}
interface Splitter {
String[] GetStringArrayOfNumbers(String[] arr);
}
}
You will have to use a Hashtable instead of a list of objects.( I am assuming that you will need to search through the list for a given entry using the First alphabet as key - This will be very laborious if you want to use a List ).
In the method SplittingHelper , provide your custom logic to parse the string of numbers and return another string[] of numbers.
I don't understand your goal, but for 'an object with 2 parts' you might consider storing them in a Hashtable: http://download.oracle.com/javase/6/docs/api/java/util/Hashtable.html

Categories

Resources