Separate values from List

Asked

Viewed 1,045 times

0

I’m using List to sort some values, but I need to separate them after I manipulated the values.

List<Map.Entry<String,Integer>> lista = new ArrayList<Map.Entry<String,Integer>>(fila);

And to print I’m using:System.out.println(lista);

And so it returns to me all the elements of the list. [c=30, e=25, b=20].

My intention would be to pass this to an array, for example, because my list is small (as in case 3). 'Cause if you go to a vector, I can only access the position I want.

  • 1

    You can only access the position you want using Arraylist as well, try this: lista.get(0);, it will return you only the first element of the list. This is no longer enough for you?

  • I completely forgot about . get(). I will use it to use the pass to vector, I need to work with vector in this part. Thank you @Math

  • 1

    To transform from Arraylist to Vector you can do so: Integer vetor[] = lista.toArray(new Integer[lista.size()]);

  • 1

    @Math I will use this way that you yourself said... thanks again! As always you saving me... I owe you beers, in case you drink :D

3 answers

4


One java.util.List can be accessed directly by the index, as below:

List<Integer> list = ...
Integer first = list.get(0);
Integer last = list.get(list.size() - 1);

But if you still wish to turn her into one array, utilize:

Object[] array = list.toArray();

or

Integer[] array = list.toArray(new Integer[0]);

Reference and more infortmasons: http://docs.oracle.com/javase/6/docs/api/java/util/List.html

  • Better than that, that’s all.

  • 1

    Your last line of code returned me the following error: Type mismatch: cannot convert from Object[] to Integer[]. There’s something wrong there, no?

  • It’s true! list.toArray() always returns a Object[], to return a defined type, the other method must be used toArray(...), as follows: list.toArray(new Integer[0]). Detailed documentation

  • 1

    Now it worked :) how about [Dit] your answer and fix such information?

1

To return a given value from a list position you can run the following code:

System.out.println(list.get(Indice));

I think you don’t need to pass your list to an array because an array only "works" with a type of data, but in the case you have a MAP works with the concept of key-value, ie, list has a key and value associated.

0

Do not use vector, use maps (Map) or implement hashCode and and equals of the object and work as follows.

List<Integer> lista = new ArrayList<Integer>();
lista.add(new Integer(30));
lista.add(new Integer(25));
lista.add(new Integer(20));
Integer oject = new Integer(25);

int index = lista.indexOf(oject);
if (index > -1)
{
   System.out.println(lista.get(index));
}

In my case my object is Integer as you have, but can make an object as needed and will be the same formula. lista.indexOf(oject), so you take any position dynamically.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.