0

If I have Arraylist<Integer> how can I do convert it to ArrayList<String>

final ArrayList<Integer> arrayList = 
    new ArrayList<Integer>(asList(19,85,955,9,2,62,96,2,6,26,2,26,2));

the Toast did not print any think on the Screen

ListView listView=findViewById(R.id.arraylistv);
     final ArrayList<Integer> arrayList=new ArrayList<Integer>(asList(19,85,955,9,2,62,96,2,6,26,2,26,2));
    final ArrayAdapter< Integer> arrayAdapter =new ArrayAdapter<Integer>(this , android.R.layout.simple_list_item_activated_1,arrayList);
    listView.setAdapter(arrayAdapter);
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            Toast.makeText(getApplicationContext(),"your num is  "+arrayList,Toast.LENGTH_LONG);
        }
    });
5
  • 1
    It's already an ArrayList? Commented Nov 23, 2018 at 21:39
  • What do you mean? As flakes said it is already an ArrayList? How do you convert an int to an int? Commented Nov 23, 2018 at 21:41
  • Do you mean how to populate a List with values using asList? Then you miss the static import java.util.Arrays. Commented Nov 23, 2018 at 21:43
  • target array contains String and not Integer? you maybe could try something like that : 'listInt.stream.map(String::valueOf).collect(Collectors.toList())' Commented Nov 23, 2018 at 22:18
  • what have you tried so far ? where is your code ? switching from Integer to String is very well documented all over the internet, did you search into the java doc or java online courses ? Commented Nov 23, 2018 at 22:39

1 Answer 1

4

You can use streams to easily convert type of a List, like this:

List<Integer> input = Arrays.asList(19,85,955,9,2,62,96,2,6,26,2,26,2);
List<String> result = input.stream().map(String::valueOf).collect(Collectors.toList());

In this case, we're using map to convert each element using String::valueOf - which basically is a function that converts the input into a string. You can replace this with any other function to convert the input type to other types.

Sign up to request clarification or add additional context in comments.

1 Comment

If you really need to to be an ArrayList you can also do input.stream().map(String::valueOf).collect(Collectors.toCollection(ArrayList::new))

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.