Search code examples
javastringcsvsplitreturn-value

java code to remove a particular value from a string with comma seprated


I have a value like the below String original = "109,107,108";

now I have to remove 107 the comma in the front and the back and should get the output of the string like

String new="109,108"

value to be removed can be dynamic. if say I will get the value to be removed from the string from another method.


Solution

  • You can split the string at the comma, then remove the undesired values and join it again. Here's an example doing this using the Java 8 Streams API:

    Arrays.stream("1,2,3".split(","))
        .filter(part -> !part.equals("2"))
        .collect(Collectors.joining(","))
    

    Also I noticed you have the "CSV" tag in your question. If you plan to parse a CSV it would probably be better use a library like fast-csv or commons-csv instead. They will be more optimized and also support more complex cases like escapes.