-1

I have a scenario in which if the user select any option from drop-down then that value is going to server as ArrayList. And if the user does not select anything then the default value is going to server as String. In java I have to convert the value to string(if i get ArrayList I have to convert that into string if i get string I have to store as it is. What is the best way to do this with minimal code?

I am trying below code :

String encoding =  myMap.get("encoding").toString();

encoding = encoding.replaceAll("\\[\\]", ""); \\removing brackets
Sampath Wijesinghe
  • 789
  • 1
  • 11
  • 33
ramya
  • 43
  • 1
  • 6

3 Answers3

0

Instead of the regex you're currently using, use [\\[\\]].

List<Integer> list = Arrays.asList(1,2,3,4,5);
String s = list.toString().replaceAll("[\\[\\]]", "");
System.out.println(s);  

Or you can use substring, like

String s = list.toString().substring(1, list.toString().length()-1);
dumbPotato21
  • 5,669
  • 5
  • 21
  • 34
0

I think you need to check if object converted to string is or is not array,because they are converted to string differently:

public String listToString(List<Object> list) {
        StringBuilder sb = new StringBuilder();

        for (Object object : list) {
            if (object != null) {
                if (object.getClass().isArray()) {
                    sb.append(Arrays.toString((Object[]) object));
                } else {
                    sb.append(object.toString());
                }
            }
        }
        return sb.toString();
    }
Jay Smith
  • 2,331
  • 3
  • 16
  • 27
0

You should never ever rely on things like list.toString().replaceAll("[\\[\\]]", "") because they are just an specific implementation of the toString method for the list and can be changed any moment making your code to crash...

Using join since java8

List<Object> olist = Arrays.asList(1, 2, 3, 4, 5);
List<String> sList = olist.stream().map(String::valueOf).collect(Collectors.toList());
String results = String.join(",", sList);
System.out.println(results);
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
  • i have a map and the value of map may be either arralylist which has only one element or a string. What i am doing now is getting the value from the map(it may be arraylist with one element or a string) and converting it into string using Tostring then removing the bracket String encoding = myMap.get("encoding").toString(); – ramya Jun 07 '17 at 05:45