0

I have a list like this :

List<List<String>> myList = new ArrayList<List<String>>();

that I fill with other lists :

List<String> lst = new ArrayList<String>();
String val1;
String val2; 
val1 = "java";
val2 = "c++";
lst.add(val1);
lst.add(val2);
myList.add(lst);

List<String> lst2 = new ArrayList<String>();
val1 = "pizza";
val2 = "fruit";
lst.add(val1);
lst.add(val2);
myList.add(lst);

I want to get the elements of the list by giving index something like :

String valeur = myList[0].val1 ;
String valeur2 = myList[1].val2 ;

which of course is a wrong way; I don't know how to do this; I read something about closures but I don't know what is it .. any help will be apprecdiated , and I hope my question is clear don't hesitate to correct or ask me if something is wrong.

Thank you.

12
  • 2
    myList.get(0).get(0);. If you want to access the values by name, then you will need to use a Map. See Collections Trail for more details Commented Dec 13, 2015 at 23:28
  • @MadProgrammer really a quick answer , I'm going to try this now. Commented Dec 13, 2015 at 23:29
  • I see there is already an answer. But replace also the declaration with: List<List<String>> myList = new ArrayList<>(); Commented Dec 13, 2015 at 23:31
  • @LowLevel While I don't disagree, it won't make a difference to the OP's problem, but will mean they can type less, so you might use "You can also use...", just in case the OP sees it as a requirement to solve there problem ;) Commented Dec 13, 2015 at 23:34
  • @LowLevel please explain to me why this declaration is more good than what I did . If you don't mind Commented Dec 13, 2015 at 23:35

2 Answers 2

4

Use List#get()

Returns the element at the specified position in this list.

String valeur = myList.get(index).get(index);
Sign up to request clarification or add additional context in comments.

Comments

0

try this String valeur = myList.get(0).get(0)

1 Comment

How does this answer improve the other answer (stackoverflow.com/a/34257681/18980756)?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.