1

I have multiple String[], some of them start with a comma. How i can remove this comma in a loop on all of the Arrays.

result:

[,a,b,c,d]
[e,f,g,h,i]
[,j,k,l,m,n]
[w,x,y,z]

Code:

        HashMap<String, String[]> newHashMap = new HashMap();
        String[] baseVectorArray;
        for (String name : externalMap.keySet()) {
            if (!name.isEmpty()) {
                StringBuilder bv = new StringBuilder();
                HashMap<String, List<String>> l = oldHashMap.get(name);
                List<String> list_of_names;
                for (String id : l.keySet()) {
                    list_of_authors = l.get(id);
                    for (String s : list_of_names) {
                        bv.append(s);
                        bv.append(", ");
                    }
                }
                bv.deleteCharAt(bv.lastIndexOf(","));
                String bvs = bv.toString();
                String[] bva = bvs.split(",");

                System.out.println(Arrays.toString(bva));
                newHashMap.put(name, bva);
            }
        }
Deksterious
  • 116
  • 2
  • 12
  • Cool, your problem makes sense. But you forgot to post your code. Please edit your question and post the code that you wrote when you tried to solve this yourself. – Kon Jan 23 '16 at 01:29
  • 1
    This is not clear. How did the output you are showing get created? A `String[]` does not contain commas, those are part of printed output, in which case you are dealing with empty string elements in a `String[]`, not leading commas. Or you could be looking at string values instead of `String[]`. We cannot tell. Can you add the code that produced the output in your question? – Jim Garrison Jan 23 '16 at 01:30
  • thanks for your reply. i posted my code. – Deksterious Jan 23 '16 at 01:49
  • 1
    Possible duplicate of [In Java, remove empty elements from a list of Strings](http://stackoverflow.com/questions/5520693/in-java-remove-empty-elements-from-a-list-of-strings) – sinclair Jan 23 '16 at 01:53

2 Answers2

0

possible solution:

for (String s : list_of_names) {
   bv.append(s.startsWith(',') ? s.substring(1) : s);
   bv.append(", ");
}

basically we're checking if it starts with comma. if so, we ignore it.

If you're using Java 8, perhaps you should refactor your code to a lambda join:

String bv = list_of_names.stream()
 .map(s -> s.startswith(",") ? s.substring(1) : s)
 .collect(Collectors.joining(", "));

in this case, this is not needed: bv.deleteCharAt(bv.lastIndexOf(","));

Luís Soares
  • 5,726
  • 4
  • 39
  • 66
0
String[] array = {"", "a", "b", "c", "d"};

List<String> list = new ArrayList<>(Arrays.asList(array));
list.removeAll(Arrays.asList("", null));
array = list.toArray(new String[list.size()]);

System.out.println(Arrays.toString(array));

Output: [a, b, c, d]

sinclair
  • 2,812
  • 4
  • 24
  • 53