Sorting a String using java collections - java

I am attaching following code and i want to sort this as
class sort{
public static void main(String args[])
{String a ="this is a kiran";
StringTokenizer st =new StringTokenizer(a);
List f=new ArrayList();
f.add(st);
Collections.sort(f);
System.out.println("after sortting "+f);
}
}
I want output as:
a
is
kiran
this
But i am getting an exception as:-
Exception in thread "main" java.lang.ClassCastException: java.util.StringTokenizer cannot be cast to java.lang.Comparableat java.util.Collections.sort(UnknownSource)atcom.sort.main(Sort.java:18)

Change your code. There are some mistakes you need to correct.
String a ="this is a kiran";
StringTokenizer st =new StringTokenizer(a);
List<String> f=new ArrayList<>(); // use String type list
while (st.hasMoreTokens()){ // add all tokens by iterating st
f.add(st.nextToken()); // add tokens to list
}
Collections.sort(f);
System.out.println("after sorting "+f);
Out put:
after sorting [a, is, kiran, this]
Now you are getting sorted list

The problem is here:
f.add(st);
You are adding StringTokenizer to the list, instead of adding the individual tokens. Changing the code to use generics would have helped: if you declare your List as List<String>, the code wouldn't compile, pointing you in the right direction:
List<String> f=new ArrayList<String>();
Add a while loop to collect tokens from st, and add them to f one by one.
P.S. Since this is almost certainly a learning exercise, I am not going to spoil the fun for you by completing your code.

You can also use hasMoreElements() and nextElement()
class sort{
public static void main(String args[]) {
String a ="this is a kiran";
StringTokenizer st =new StringTokenizer(a);
ArrayList<String> f=new ArrayList<String>(); // use String type list
while (st.hasMoreElements()){ // add all by iterating st
f.add((String) st.nextElement()); // add tokens to list
}
Collections.sort(f);
System.out.println("after sorting "+f);
}
}

Consider using String.split() to split your string.
Class names should be nouns,
method names should be verbs or verb phrases,
and you should use generics.
public static void main(String[] arguments)
{
String input = "this is hootberry sause";
String[] inputArray;
List<String> inputList = new ArrayList<String>();
inputArray = input.split(" ");
Collections.addAll(inputList, inputArray);
Collections.sort(inputList);
System.out.println("Before sort: " + input);
System.out.println("After sort: " + inputList);
}

Related

How do I remove the whitespace after each comma in an ArrayList?

I am struggling with removing spaces in an arraylist of strings.
Say the user input is as follows: "I walked my dog", my code outputs this:
[I, walked, my, dog]
I want it to have no spaces as such:
[I,walked,my,dog]
I tried to remove whitespace on each individual string before I add it to the arrayList, but the output still has the spaces.
Scanner input = new Scanner(System.in);
ArrayList<String> userWords = new ArrayList<String>();
ArrayList<String> SplituserWords = new ArrayList<String>();
System.out.println("Please enter your phrase: ");
userWords.add(input.nextLine());
for (int index = 0; index < userWords.size(); index++) {
String[] split = userWords.get(index).split("\\s+");
for (String word : split) {
word.replaceAll("\\s+","");
SplituserWords.add(word);
}
System.out.println(SplituserWords);
I suggest just taking advantage of the built-in Arrays#toString() method here:
String words = input.nextLine();
String output = Arrays.toString(words.split(" ")).replace(" ", "");
System.out.println(output); // [I,walked,my,dog]
When you are writing System.out.println(SplituserWords);, you are implicitly calling ArrayList#toString() which generates the list's string and that includes spaces after commas.
You can instead generates your own string output, for example with:
System.out.println("[" + String.join(",", SplituserWords) + "]");
If you insist on using List, it will do it for you.
String input = "I walked my dog";
List<String> SplitUserWords = Arrays.asList(input.split(" "));
String output = SplitUserWords.toString().replace(" ", "");
System.out.println(output); //[I,walked,my,dog]
I tried to remove whitespace on each individual string before I add it to the arrayList, but the output still has the spaces.
That won't work because that isn't the problem. The issue is that it is the list implementation that formats the output for you inserts a space after each comma. It does this in the toString() method. To avoid having to explicitly call replace each time you can also do it like this by overidding toString() when you create your List.
List<String> myList = new ArrayList<>(List.of("I","walked","my", "dog")) {
#Override
public String toString() {
// use super to call the overidden method to format the string
// then remove the spaces and return the new String
return super.toString().replace(" ", "");
}
};
System.out.println(myList);
myList.addAll(List.of("and", "then","fed", "my", "cat"));
System.out.println(myList);
prints
[I,walked,my,dog]
[I,walked,my,dog,and,then,fed,my,cat]
You can also subclass ArrayList as follows. Here I have added the three constructors that ArrayList implements. Note that is is a somewhat extreme solution and may not be worth it for occasionally reformatting of the output. I included it for your consideration.
class MyArrayList<E> extends ArrayList<E> {
public MyArrayList() {
super();
}
public MyArrayList(int capacity) {
super(capacity);
}
public MyArrayList(Collection<? extends E> c) {
super(c);
}
#Override
public String toString() {
return super.toString().replace(" ", "");
}
}
And it would work like so.
MyArrayList<String> myList = new MyArrayList<>(List.of("This", "is", "a","test."));
System.out.println(myList);
prints
[This,is,a,test.]

How to remove comma from HashSet String java

I have a HashSet String ['a','b','c']. How can I print the String abc?
My code:
import java.util.*;
public class Main
{
public static void main(String[] args) {
HashSet<Character>h=new HashSet<>();
h.add('a');
h.add('b');
h.add('c');
// if here i am print HashSet element then print
System.out.println(h); //[a,b,c]
// now i HashSet convert in String
String res=h.toString();
// when i try to print String then print [a,b,c]
System.out.println(res); // [a,b,c]
//but i am not interest in this result becuase i wnat to print only abc remove all brackets [] ,and , commas
}
You just have to use String.join() as followed
System.out.println(String.join("",h));
If you are using Java 8 or later then you can use Java Stream API, or Iterable.forEach():
public class HashSetExample {
public static void main(String[] args) {
Set<String> set = new HashSet<>(Arrays.asList("a", "b", "c", "d", "e"));
System.out.println("System.out.println(set): " + set);
System.out.print("Using .forEach() method: ");
set.forEach(System.out::print);
System.out.println();
System.out.print("Using Stream API: ");
set.stream().forEach(System.out::print);
System.out.println();
}
}
The output will be:

String inside ArrayList<String[]>

How to check whether a specific String is present inside ArrayList<String[]>?
Whether I need to iterate each item and check for the string or any specific method for this purpose is present (like ArrayList.contains() )?
Tried ArrayList.contains() but not working in my case.
It is not an ArrayList <String> it is ArrayList<String[]> so this question is not a duplicate one and am asking this for a curiosity whether any special method is present or not
This is a example program to get what you asked for... hope it helps
public static void main(String[] args) {
ArrayList<String []> a = new ArrayList<>();
String b[] = {"not here","not here2"};
String c[] = {"not here3","i'm here"};
a.add(b);
a.add(c);
for (String[] array : a) {// This loop is used to iterate through the arraylist
for (String element : array) {//This loop is used to iterate through the array inside the arraylist
if(element.equalsIgnoreCase("i'm here")){
System.out.println("found");
return;
}
}
}
System.out.println("match not found");
}
You can do it easily with streams:
String contains;
List<String[]> strings;
boolean isPresent = strings.stream().flatMap(Arrays::stream).anyMatch(contains::equals);
Well, you need to traverse whole list and then traverse each array inside it to find the item.
String valToBeSearched="abc";
for(String [] arr: list)
{
for(String str: arr)
{
if(str.equals(valToBeSearched)){ // do your stuff}
}
}
Using Java 8 streams, you can do this:
public boolean containsString(List<String[]> list, String s) {
// Gives you a Stream<String[]>.
return list.stream()
// Maps each String[] to Stream<String> (giving you a
// Stream<Stream<String>>), and then flattens it to Stream<String>.
.flatMap(Arrays::stream)
// Checks if any element is equal to the input.
.anyMatch(Predicate.isEqual(s));
}
You could iterate over the ArrayList with two for-each loops:
import java.util.Arrays;
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
ArrayList<String[]> arrayList = new ArrayList<String[]>();
String[] fruit = {"Apple", "Banana"};
String[] pets = {"Cat", "Dog"};
arrayList.add(fruit);
arrayList.add(pets);
System.out.println(Arrays.deepToString(arrayList.toArray())); //[[Apple, Banana], [Cat, Dog]]
System.out.println(arrayListContains(arrayList, "Apple")); //true
System.out.println(arrayListContains(arrayList, "Orange")); //false
}
public static boolean arrayListContains(ArrayList<String[]> arrayList, String str) {
for (String[] array : arrayList) {
for (String s : array) {
if(str.equals(s)) {
return true;
}
}
}
return false;
}
}
Try it here!
Try to take a look at Guava Iterables.concat().
It can be used to flatten Iterable of Iterables, i'm not sure it will work on an Iterable of Array but it's just a little transformation...
If you can flatten your list, you could then use the "contains" method on the result.

ArrayList constructor and use in methods

Hi I am a novice n just learning java. I was studying ArrayList n came accross this code for example {CODE1}.
I would like to use the same code but add a ArrayListDemo constructor n create methods such as displayList and removeElement.
I tried to find such examples but i did not understand them.
This is the code that i tried {CODE2} With my modifications please tell me where m going wrong.
***CODE1 {Example Code}****
import java.util.ArrayList;
public class AraryListDemo {
public static void main(String[] args) {
ArrayList al = new ArrayList();
System.out.print("Initial size of al : " + al.size());
System.out.print("\n");
//add.elements to the array list
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
al.add(1,"A2");//inserts objects "A2" into array at index 1
System.out.print("size of al after additions " + al.size());
System.out.print("\n");
//display the array list
System.out.print("contents of al: " + al );
System.out.print("\n");
//Remove elements from the array list
al.remove("F");
al.remove(2);
System.out.print("size of after deletions : " + al.size());
System.out.print("\n");
System.out.print("contents of al:" + al);
}
}
********CODE 2 {My Modifications}*************
class ArrayListDemo
{
ArrayList<String> al;//variable declared
ArrayListDemo() throws IOException//try constructor for this
{
al = new ArrayList<String>();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("\n Enter Student Names");
for(int i=0;i<=5;i++)// will dispaly
{
al.add(br.readLine());
}
}
void dispList(ArrayList <String> al)
{
System.out.println("\n Display Student Names");
for(String str : al)
{
System.out.println("\t Name : "+str+"\n");
}
}
}
class DisplayArrayList
{
public static void main(String []args) throws IOException
{
ArrayList <String> al = new ArrayList <String>();
ArrayListDemo e = new ArrayListDemo();
e.dispList(al);
}
}
ArrayList <String> al = new ArrayList <String>();
ArrayListDemo e = new ArrayListDemo();
e.dispList(al);
In the above code, you are creating a new ArrayList al, and passing the same to dispList() method, which doesn't iterate, because the al has no elements.
I guess you wanted to iterate through the elements which you created within ArrayListDemo. So you may want to write dispList() method as below, which will now use ArrayList defined within the class
void dispList() //method parameter "al" is removed now and, al is the al of ArrayListDemo
{
System.out.println("\n Display Student Names");
for(String str : al) //here al refers to ArrayList defined within the class
{
System.out.println("\t Name : "+str+"\n");
}
}
It's not clear what exactly you're asking, but I note that you have a problem with your declarations (plural) of al: You have one ArrayList named al in your main, and you have another one that belongs to ArrayListDemo. You're reading values into the second one and then printing out the (empty) first one.
You really don't need a separate class with a constructor here. You can just have two static methods readList(List<String> al) and dispList(List<String> al). If you really do want to have a separate class, pick one place to store the List (either in main or in the class).
As a note, it's generally a good idea to use the most general type for variables and method parameters that you can. You're declaring an ArrayList, which is fine, but if you make your variable and parameters Lists, your code is more flexible.
The easiest (but not a prefered) solution to make your effort work is to pass the array to the displist() method that was filled by the constructor.
public static void main(String []args) throws IOException
{
ArrayListDemo e = new ArrayListDemo();
e.dispList(e.al);
}
Your code runs as following :-
ArrayList <String> al = new ArrayList <String>(); // Initialise an ArrayList of type string
ArrayListDemo e = new ArrayListDemo(); // Initialised class ArrayListDemo
class constructor reads data from user input and add to ArrayList a1 by br.readLine()
e.dispList(al); iterates the ArrayList instance a1 and print its output.

How to convert a String into an ArrayList?

In my String, I can have an arbitrary number of words which are comma separated. I wanted each word added into an ArrayList. E.g.:
String s = "a,b,c,d,e,.........";
Try something like
List<String> myList = new ArrayList<String>(Arrays.asList(s.split(",")));
Arrays.asList documentation
String.split documentation
ArrayList(Collection) constructor documentation
Demo:
String s = "lorem,ipsum,dolor,sit,amet";
List<String> myList = new ArrayList<String>(Arrays.asList(s.split(",")));
System.out.println(myList); // prints [lorem, ipsum, dolor, sit, amet]
This post has been rewritten as an article here.
String s1="[a,b,c,d]";
String replace = s1.replace("[","");
System.out.println(replace);
String replace1 = replace.replace("]","");
System.out.println(replace1);
List<String> myList = new ArrayList<String>(Arrays.asList(replace1.split(",")));
System.out.println(myList.toString());
In Java 9, using List#of, which is an Immutable List Static Factory Methods, become more simpler.
String s = "a,b,c,d,e,.........";
List<String> lst = List.of(s.split(","));
Option1:
List<String> list = Arrays.asList("hello");
Option2:
List<String> list = new ArrayList<String>(Arrays.asList("hello"));
In my opinion, Option1 is better because
we can reduce the number of ArrayList objects being created from 2 to 1. asList method creates and returns an ArrayList Object.
its performance is much better (but it returns a fixed-size list).
Please refer to the documentation here
Easier to understand is like this:
String s = "a,b,c,d,e";
String[] sArr = s.split(",");
List<String> sList = Arrays.asList(sArr);
Ok i'm going to extend on the answers here since a lot of the people who come here want to split the string by a whitespace. This is how it's done:
List<String> List = new ArrayList<String>(Arrays.asList(s.split("\\s+")));
If you are importing or you have an array (of type string) in your code and you have to convert it into arraylist (offcourse string) then use of collections is better. like this:
String array1[] = getIntent().getExtras().getStringArray("key1"); or String array1[] = ... then
List allEds = new ArrayList(); Collections.addAll(allEds, array1);
You could use:
List<String> tokens = Arrays.stream(s.split("\\s+")).collect(Collectors.toList());
You should ask yourself if you really need the ArrayList in the first place. Very often, you're going to filter the list based on additional criteria, for which a Stream is perfect. You may want a set; you may want to filter them by means of another regular expression, etc. Java 8 provides this very useful extension, by the way, which will work on any CharSequence: https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html#splitAsStream-java.lang.CharSequence-. Since you don't need the array at all, avoid creating it thus:
// This will presumably be a static final field somewhere.
Pattern splitter = Pattern.compile("\\s+");
// ...
String untokenized = reader.readLine();
Stream<String> tokens = splitter.splitAsStream(untokenized);
If you want to convert a string into a ArrayList try this:
public ArrayList<Character> convertStringToArraylist(String str) {
ArrayList<Character> charList = new ArrayList<Character>();
for(int i = 0; i<str.length();i++){
charList.add(str.charAt(i));
}
return charList;
}
But i see a string array in your example, so if you wanted to convert a string array into ArrayList use this:
public static ArrayList<String> convertStringArrayToArraylist(String[] strArr){
ArrayList<String> stringList = new ArrayList<String>();
for (String s : strArr) {
stringList.add(s);
}
return stringList;
}
Let's take a question : Reverse a String. I shall do this using stream().collect(). But first I shall change the string into an ArrayList .
public class StringReverse1 {
public static void main(String[] args) {
String a = "Gini Gina Proti";
List<String> list = new ArrayList<String>(Arrays.asList(a.split("")));
list.stream()
.collect(Collectors.toCollection( LinkedList :: new ))
.descendingIterator()
.forEachRemaining(System.out::println);
}}
/*
The output :
i
t
o
r
P
a
n
i
G
i
n
i
G
*/
This is using Gson in Kotlin
val listString = "[uno,dos,tres,cuatro,cinco]"
val gson = Gson()
val lista = gson.fromJson(listString , Array<String>::class.java).toList()
Log.e("GSON", lista[0])
I recommend use the StringTokenizer, is very efficient
List<String> list = new ArrayList<>();
StringTokenizer token = new StringTokenizer(value, LIST_SEPARATOR);
while (token.hasMoreTokens()) {
list.add(token.nextToken());
}
If you're using guava (and you should be, see effective java item #15):
ImmutableList<String> list = ImmutableList.copyOf(s.split(","));

Categories

Resources