String function list in java

Initialize List of String in java

In this post, we will see how to initialize List of String in java.

Can you initialize List of String as below:

You can’t because List is an interface and it can not be instantiated with new List() .

You need to instantiate it with the class that implements the List interface.

Here are the common java Collections classes which implement List interface.

In most of the cases, you will initialize List with ArrayList as below.

If you are using java 7 or greater than you can use diamond operator with generics.

Initialize List of Strings with values

There are many ways to initialize list of Strings with values.

Arrays’s asList

You can use Arrays’s asList method to initialize list with values.

Stream.of (Java 8)

You can use java 8‘s Stream to initialize list of String with values.

List.of (Java 9)

Finally, java has introduced a of() method in List class to initialize list with values in java 9.

Using ArrayList’s add method

You can obviously initialize ArrayList with new operator and then use add method to add element to the list.

Using guava library

You can use guava library as well.

Here is the complete example.

That’s all about how to initialize List of String in java.

Was this post helpful?

Share this

Author

Convert UUID to String in Java

Table of ContentsIntroductionUUID class in JavaConvert UUID to String in Java Introduction In this article, we will have a look on How to Convert UUID to String in Java. We will also shed some light on the concept of UUID, its use, and its corresponding representation in Java class. Let us have a quick look […]

Repeat String N times in Java

Table of ContentsIntroductionWhat is a String in Java?Repeat String N times in JavaSimple For Loop to Repeat String N Times in JavaUsing Recursion to Repeat String N Times in JavaString.format() method to Repeat String N Times in JavaUsing String.repeat() method in Java 11 to Repeat String N TimesRegular Expression – Regex to Repeat String N […]

How to Replace Space with Underscore in Java

Table of ContentsReplace space with underscore in java1. Using replace() method2. Using replaceAll() method Learn about how to replace space with underscore in java. Replace space with underscore in java 1. Using replace() method Use String’s replace() method to replace space with underscore in java. String’s replace() method returns a string replacing all the CharSequence […]

How to Replace Comma with Space in Java

Table of ContentsReplace comma with space in java1. Using replace() method2. Using replaceAll() method Learn about how to replace comma with space in java. Replace comma with space in java 1. Using replace() method Use String’s replace() method to replace comma with space in java. Here is syntax of replace() method: [crayon-64c57e41b1814037362476/] [crayon-64c57e41b181e228646233/] Output: 1 […]

Remove Parentheses From String in Java

Table of ContentsJava StringsRemove Parentheses From a String Using the replaceAll() MethodRemove Parentheses From a String by TraversingConclusion Java uses the Strings data structure to store the text data. This article discusses methods to remove parentheses from a String in Java. Java Strings Java Strings is a class that stores the text data at contiguous […]

Escape percent sign in java

Escape percent sign in String’s format method in java

Table of ContentsEscape Percent Sign in String’s Format Method in JavaEscape Percent Sign in printf() Method in Java In this post, we will see how to escape Percent sign in String’s format() method in java. Escape Percent Sign in String’s Format Method in Java String’s format() method uses percent sign(%) as prefix of format specifier. […]

Источник

How do I replace characters in every string in my list in java?

I know of the Collections.replaceAll(list, to replace, replace with) , but that only applies to Strings that are that exact value, not every instance in every String.

4 Answers 4

What you must is to apply the replace function to each of the string in your list.

And as the strings are immutable you will have to create another list where string with no space will be stored.

List result = new ArrayList<>(); for (String s : source)

Immutable means that object can not be changed, it must be created new one if you want to change the state of it.

String s = "how are you"; s = s.replaceAll("\\s+", ""); 

The function replaceAll returns the new string if you did not assign it to variable s then would still have spaces.

Sorry, I forgot to comment (didn’t know I could), thanks for the help, worked like a charm! I’m glad I’ve found a new helpful community for all my programming problems!

It doesn’t sound very useful.

import java.util.Arrays; import java.util.List; /** * http://stackoverflow.com/questions/20760578/how-do-i-replace-characters-in-every-string-in-my-list-in-java/20760659#20760659 * Date: 12/24/13 * Time: 7:08 AM */ public class SpaceEater < public static void main(String[] args) < ListstringList = Arrays.asList(args); System.out.println("before: " + stringList); for (int i = 0; i < stringList.size(); ++i) < stringList.set(i, stringList.get(i).replaceAll("\\s+", "")); >System.out.println("after : " + stringList); > > 

disrvptor was correct — original snippet did not alter the list. This one does.

Источник

Decompose a String into Array of Long or List of Long without Loop in JAVA

I want to decompose a String array into Long array or List. I don’t want to use Loop. Is there any Java Method to do this.

So the array contains string representations of long s? You need to be a lot more specific and include both desired in-/output and your attempt at solving it yourself.

@milkplusvellocet: No, the other question is about parsing a String into an array of ints. This question is about «converting» a String array into a Long array (without defining the «converting» part)

Perhaps OP should clarify what they mean. This popped up a very short time after a very similarly worded question which is why it stood out to me as a duplicate. Anyway the essence of the question (not wanting to use a loop) is the same.

6 Answers 6

Simplified Eugene answer with Guava library. Since Guava 16.0.

List longList = Lists.transform(Arrays.asList(stringArray), Longs.stringConverter()); 

Update: Solution with Java 8, without 3th party libraries:

List longList = Stream.of(stringArray).map(Long::valueOf).collect(Collectors.toList()); 

There is no O(1) operation to «convert» a String[] (with numeric strings) to a long[] . It will always be O(n), if the loop visible or hidden in some thirdparty method.

If you don’t want to «see» the loop, simply implement a method

Long[] pseudoOneStepConversion(numbers); 
privat Long[] pseudoOneStepConversion(String[] numbers)

We can do it recursively too — it is still O(n), less performant and doesn’t look like a loop:

public static void main(String[] args) < Listtarget = new ArrayList(); copy(new String[], target, 0); System.out.println(target); > private static void copy(String[] source, List target, int index)

Note — because I start getting downvotes for the recursion example: It is purely academic and not inteded for use in production code — thought, that was clear 😉

Источник

Best way to build a delimited string from a list in java

I have a list of objects, and each object has a string property. For example, I have a List and each Person has a firstName property. I want to build a comma-delimited, quoted string that looks like this:

Considering that java doesn’t seem to have a join method (and besides, this is a bit more complicated than a simple delimited string), what’s the most straightforward way to do this? I’ve been trying to code this for a bit but my code’s gotten very messy and I could use some fresh input.

I don’t think it’s a duplicate. It’s not just a simple join with a delimiter, I also want to surround each component in quotes

@Tom Hawtin — tackline — but what about the first and last quote, then? They have to be hardcoded in? e.g. «‘» + myJoinMethod(myList, «‘, ‘») + «‘» ? And there’s no simpler way?

9 Answers 9

I used this for the same issue (Apache StringUtils)

String joined = "'" + StringUtils.join(arrayOrList,"','") + "'"; 

If you want to do it simply and manually, you could do something like this:

String mystr = ""; for(int i = 0; i < personlist.size(); i++) < mystr += "\'" + personlist.get(i).firstName + "\'"; if(i != (personlist.size() - 1)) < mystr += ", "; >> 

Now mystr contains your list. Note that the comma is only added if we are not acting on the last element in the list (with index personlist.size() — 1).

Of course, there are more elegant/efficient methods to accomplish this, but this one is, in my opinion, the clearest.

Doing lots of String concatenation is evil in Java, and that conditional inside the loop will mean lots of unnecessary checks. These effects combined will yield poor performance for large lists of people.

You are right; however, the context seems to favor simplicity over performance. But I agree: this is not the appropriate solution for any production application. For the purposes of learning, though, I think it is a start. 🙂

Just use the most straightforward way. Have a StringBuilder , loop over the List , surround each item with quotes, append it to builder and if there’s more to come, append the comma.

StringBuilder builder = new StringBuilder(); for (int i = 0; i < persons.size(); i++) < builder.append("'").append(persons.get(i)).append("'"); if (i < persons.size() - 1) < builder.append(", "); >> String string = builder.toString(); 

Alternatively, you can also use the Iterator :

StringBuilder builder = new StringBuilder(); for (Iterator iter = persons.iterator(); iter.hasNext();) < builder.append("'").append(iter.next()).append("'"); if (iter.hasNext()) < builder.append(", "); >> String string = builder.toString(); 

Note that using a StringBuilder is preferred over using += string concatenation since the latter implicitly creates a new string instance on the heap which might be performance and memory hogging when you’ve a lot of items.

String quotedAndDelimited = Arrays.stream(values).collect(Collectors.joining("\",\"","\"","\"")); 

This provides «,» as the delimited, and a prefix and suffix of «.

Here is unit test with expectations:

import static java.util.Arrays.*; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*; import org.junit.Test; public class JoinerTest < private static final ConverterPERSON_CONVERTER = new Converter() < @Override public String convert(Person object) < return object.getFirstName(); >>; @Test public void shouldPresentFirstNames() < // given Person person1 = new Person(); person1.setFirstName("foo"); Person person2 = new Person(); person2.setFirstName("bar"); Joinerjoiner = new Joiner(", ", "\'"); // when String firstNames = joiner.join(PERSON_CONVERTER, asList(person1, person2)); // then assertThat(firstNames, is("\'foo\', \'bar\'")); > > 

Converter is just an interface:

public interface Converter

public class Joiner  < private final String delimiter; private final String quote; public Joiner(String delimiter, String quote) < this.delimiter = delimiter; this.quote = quote; >public String join(Converter converter, Iterable objects) < StringBuilder builder = new StringBuilder(); for (T object : objects) < String string = converter.convert(object); builder.append(quote); builder.append(string); builder.append(quote); builder.append(delimiter); >if (builder.length() > 0) < builder.setLength(builder.length() - delimiter.length()); >return builder.toString(); > > 

By using different converters it is easy to join properties of different types.

The key advantage of this is that 90% of your execution time will probably be done in the inner while loop, and this solution only requires one comparison to determine if we need to exit the inner while loop.

Other solutions work too, but a solution that looks like:

embeds an unnecessary if statement within the while loop. This means an extra comparison will have to be made for each element, when the only differing element would be the last one.

By shifting the comparison for checking if the element is the last one to a comparison if there is more than one element, we only need to move the appended «, » to a prepended «, » for each element other than the first

Источник

Читайте также:  Css статью в блок
Оцените статью