D
D
dc65k2021-06-17 21:47:53
Java
dc65k, 2021-06-17 21:47:53

How to sort strings in an array with further gluing in Java?

Hi everybody. I have a task with several steps.
In the loop, I need to do the following operations with a string value, if we draw an analogy with the implementation in JavaScript:

let w = i.split('').sort().join(''); 
i.split('') – создаю массив из символов
i.split('').sort() – сортирую массив по алфавиту 
i.split('').sort().join('') - массив преобразую в строку


Ex.1

package com.example.demo;

import java.util.*;

public class Test3 {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("нос");
        list.add("сон");
        list.add("снедь");
        list.add("днесь");
//        System.out.println(list);

        Anagrams anagrams = new Anagrams(list);

        anagrams.getAnagrams();
    }
}

class Anagrams {

    public List<String> words;

    public Anagrams(List<String> words) {
        this.words = words;
    }

    public boolean getAnagrams() {
        System.out.println(words);

        Map<String, String> map = new HashMap<>();

        for (int i = 0; i < words.size(); i++) {
//            System.out.println(words.get(i));

            StringBuilder word = new StringBuilder(words.get(i));
            System.out.println(word);

            String[] array = words.get(i).split(""); // создаю массив из символов
            System.out.println(Arrays.toString(array));

//            String[] sortedArray = Arrays.sort(array); // сортирую массив по алфавиту // ?

            // массив преобразую в строку // ?
        }

        return true;
    }

}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
BorLaze, 2021-06-17
@dc65k

Sort characters in a string? It is possible like this:

String input = "колобок";
String output = Stream.of(input.split(""))
                          .sorted()
                          .collect(Collectors.joining());

output: bkclooo

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question