How to make a Collection<String> object from comma separated values - java

I have a String object like
final String demoString = "1,2,19,12";
Now I want to create a Collection<String> from it. How can I do that?

Guava:
List<String> it = Splitter.on(',').splitToList(demoString);
Standard JDK:
List<String> list = Arrays.asList(demoString.split(","))
Commons / Lang:
List<String> list = Arrays.asList(StringUtils.split(demoString, ","));
Note that you can't add or remove Elements from a List created by Arrays.asList, since the List is backed by the supplied array and arrays can't be resized. If you need to add or remove elements, you need to do this:
// This applies to all examples above
List<String> list = new ArrayList<String>(Arrays.asList( /*etc */ ))

Simple and good,
List<String> list = Arrays.asList(string.split(","))

you can create a List<String> and assign it to Collection<String> as List extends Collection.
final String demoString = "1,2,19,12";
Collection<String> collection = List.of(demoString.split(","));

Related

Comparing two ArrayLists and remove duplicates from original ArrayList

I have two Custom Arraylist:
List<Item> before = new ArrayList<Item>();
List<ItemEx> after = new ArrayList<ItemEx>();
before.add(new Item(1L,"test1"));
before.add(new Item(2L,"test2"));
before.add(new Item(3L,"test3"));
after.add(new ItemEx(1L,"test4"));
after.add(new ItemEx(2L,"test5"));
after.add(new ItemEx(4L,"test6"));
after.add(new ItemEx(5L,"test7"));
I want to store the elements in the List<ItemEx> after and the element shoulds be after the removing of common element is {3L, 4L, 5L}.
FYI
List<Item> & List<ItemEx> should be SAME TYPE .
Logic
List<String> before = new ArrayList<String>();
List<String> after = new ArrayList<String>();
List<String> list_checking = new ArrayList<String>(before);
list_checking.addAll(after);
List<String> list_common = new ArrayList<String>(before);
list_common.retainAll(after);
list_checking.removeAll(list_common);
Try this :
HashSet hs = new HashSet();
hs.addAll(before);
hs.addAll(after);
after.clear();
after.addAll(hs);
Now, in after list you get desire values.
Its simple. Take a copy of the existing one into a temporary Variable if you want for future use.
ArrayList temporiginalArrList=OriginalArrayList;
//here 'T' can be a specific object to want to save
OriginalArrayList.removeAll(secondArrayList);

Is there a way to filter out the elements of a List containing object having a String element based on another List of String

I have a List of an object List<Object> which Objects contains String elements . Now There is also another List of String List<String> .
I want the first List to only contain objects which are elements of the second list.
What is the most efficient way to do this?
You can use the contains() method of the list and that's convenient in your case since it will equals() check the Strings.
e.g.
List<String> otherList = new ArrayList<>();
List<Object> test = new ArrayList<>();
Iterator<Object> it = test.iterator();
while(it.hasNext()){
if(!otherList.contains(it.next().getString())) it.remove();
}
or in Java8 streams
test.stream().filter(e -> otherList.contains(e.getString()))
.collect(Collectors.toList());
This will generate you a new List.

How to split a String to an ArrayList?

I know there is a String split method that returns an array but I need an ArrayList.
I am getting input from a textfield (a list of numbers; e.g. 2,6,9,5) and then splitting it at each comma:
String str = numbersTextField.getText();
String[] strParts = str.split(",");
Is there a way to do this with an ArrayList instead of an array?
You can create an ArrayList from the array via Arrays.asList:
ArrayList<String> parts = new ArrayList<>(
Arrays.asList(textField.getText().split(",")));
If you don't need it to specifically be an ArrayList, and can use any type of List, you can use the result of Arrays.asList directly (which will be a fixed-size list):
List<String> parts = Arrays.asList(textField.getText().split(","));
There is no such thing as a Split functionfor list, but you can do the split and then convert to a List
List myList = Arrays.asList(myString.split(","));

Separating the elements of arraylist

I have an ArrayList that contains a messageId, then a -, then a username.
Example : E123-sam
I want to divide each element of my List such that the part before the - goes to one ArrayList and the part after that goes to an other ArrayList.
How can I do it?
Assuming you have these ArrayLists:
List<String> allStrings;
// ... initialization and filling of 'allStrings'
List<String> messageIDs = new ArrayList<>();
List<String> userNames = new ArrayList<>();
you can loop through elements of the ArrayList and use String#split(delimiter) to separate the string based in the delimiter:
for (String s : allStrings) {
String[] parts = s.split("-");
messageIDs.add(parts[0]);
userNames.add(parts[1]);
}
Note: This will work if all the strings in allStrings follows the pattern "something-something". If not, then you can check if the length of parts is correct before accessing its elements, otherwise you will get a IndexOutOfBoundsException.
If you plan to use Java 8, you could do:
List<String> listOfIds = original.stream().map(e -> e.split("-")[0]).collect(Collectors.toList());
List<String> listOfUsernames = original.stream().map(e -> e.split("-")[1]).collect(Collectors.toList());

Merge 3 arraylist to one

I want to merge down 3 arraylist in one in java. Does anyone know which is the best way to do such a thing?
Use ArrayList.addAll(). Something like this should work (assuming lists contain String objects; you should change accordingly).
List<String> combined = new ArrayList<String>();
combined.addAll(firstArrayList);
combined.addAll(secondArrayList);
combined.addAll(thirdArrayList);
Update
I can see by your comments that you may actually be trying to create a 2D list. If so, code such as the following should work:
List<List<String>> combined2d = new ArrayList<List<String>>();
combined2d.add(firstArrayList);
combined2d.add(secondArrayList);
combined2d.add(thirdArrayList);
What about using java.util.Arrays.asList to simplify merging?
List<String> one = Arrays.asList("one","two","three");
List<String> two = Arrays.asList("four","five","six");
List<String> three = Arrays.asList("seven","eight","nine");
List<List<String>> merged = Arrays.asList(one, two, three);
Using Java 8 Streams:
List of List
List<List<String>> listOfList = Stream.of(list1, list2, list3).collect(Collectors.toList());
List of Strings
List<String> list = Stream.of(list1, list2, list3).flatMap(Collection::stream).collect(Collectors.toList());
Using Java 9 List.of static factory method (Warning: this list is immutable and disallows null)
List<List<String>> = List.of​(list1, list2, list3);
Where list1, list2, list3 are of type List<String>

Categories