# swifter **Repository Path**: li-lxs/swifter ## Basic Information - **Project Name**: swifter - **Description**: 封装了业务中很多常用代码 - **Primary Language**: Unknown - **License**: GPL-3.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2022-11-09 - **Last Updated**: 2025-05-06 ## Categories & Tags **Categories**: Uncategorized **Tags**: Java, java-util, 函数式, 工具包 ## README # Swifter 优雅的java函数式编程工具包 ## 工具: - 容器类 - 仿元组容器类 - 线程安全容器类 - 独占对象 - 可读写对象 - 对象池 - 业务封装容器类 - 字典树 - 缓存容器 - KV本地缓存 - 数组本地缓存 - 引用本地缓存 - 对象包装容器 - 可空对象包装容器 Option - 异常对象包装容器 Trouble - 可选对象包装容器 Either - 工具类 - http工具类 - 函数式统计工具类 - 日期工具类 - 排序工具类 - 集合工具类 - 字符串格式化工具类 - 负载均衡算法类 - 对象结构化 - HashStruct 复杂对象结构体 - StructArray 对象结构列表 - 函数式操作包装类 - 验证器 ## 安装在本地 ```shell mvn install:install-file "-Dmaven.repo.local=D:\software\maven\.m3\repository" "-Dfile=.\swifter-2.3.3.jar" "-DgroupId=lxs.swift" "-DartifactId=swifter" "-Dversion=1.0.5" ``` ### 容器类 - 仿元组容器类 lxs.swift.collector.tuple.Tuple ```java import lxs.swift.collector.tuple.*; class Demo { public static void main(String[] args) { Tuple3 tuple3 = Tuple.of(0, 1, 2); tuple3._1 += 1; int sum = tuple3.stream().mapToInt(v -> v).sum();//流 } } ``` - 线程安全容器类 lxs.swift.collector.sync.* ```java import lxs.swift.collector.sync.*; import java.util.concurrent.TimeUnit; class Demo{ public static void main(String[] args){ // 独占锁对象 { Mutexmutex=new Mutex<>("foo"); //函数式操作获取值 String s = mutex.get(v->v+" aaa");//s="foo aaa" String bar = mutex.set(v->"bar"); } // 读写锁对象 { RwLockrwLock=new RwLock<>("foo"); //函数式操作获取值 将返回值设置为新值并返回 String s = rwLock.use(v->v+" aaa"); //当有多个线程要更新时 使得只有第一个线程能更新 boolean b = rwLock.useIf(v->v+" aaa"); } // 对象池 { //动态生成对象,最大容量5,1分钟过期 Poolfactory=Pool.factory(()->"new one",5,1,TimeUnit.MINUTES); //对象列表从初始化时固定 Poolfixed=Pool.fixed("foo1","foo2","foo3"); Pool.Holder holder = factory.get(10,TimeUnit.SECONDS); String value = holder.getValue(); System.out.println(value); holder.close();//释放占用 } } } ``` - 业务封装容器类 lxs.swift.collector.Res ```java import lxs.swift.collector.Res; class Demo{ public static void main(String[] args){ Resres=Res.exec(()->{ // 业务 return "foo"; })//自动统计执行耗时 .error("系统异常")//当发生异常时返回的信息 默认打印堆栈信息 .error((err)->new Res.Error("系统异常",500))//当发生异常时返回的信息 .success("操作成功")//当操作成功时返回的信息 .success((value)->{ System.out.println("执行成功:"+value); return new Res.Success<>("bar","操作成功",200); })//当操作成功时返回的信息 .onFinally(res->{}) .respond(); Res foo = Res.ok("foo"); Res err = Res.err("异常"); } } ``` - 字典树 lxs.swift.collector.DictTree ```java import lxs.swift.collector.DictTree; import java.util.List; class Demo{ public static void main(String[] args){ DictTree dictTree = new DictTree();//初始化空树 dictTree.insert("我爱你"); List words = dictTree.matchWords("我爱你xx"); //[Word{value:"我爱你",startIndex:0,endIndex:2}] } } ``` - 缓存容器 lxs.swift.collector.cache.* ```java import lxs.swift.collector.cache.*; import lxs.swift.collector.cache.list.ListCache; import lxs.swift.collector.cache.map.MapCache; import java.util.ArrayList; import java.util.List;import java.util.concurrent.TimeUnit; class Demo{ public static void main(String[] args){ //列表缓存 ListCache cache = ListCache.builder("foo") .dataSupplier(() -> { System.out.println("更新"); List users = users(); Try.run(() -> Thread.sleep(100)).run(); return users; }) .list(new ArrayList<>()) .overTime(200) .build(); List select = cache.select((user -> user.isMale)); //kv缓存 MapCache mapCache = MapCache.builder("bar") .overtime(200)//过期时间 .checkTime(10)//轮询检查时间 .waitTime(100)//更新时等待时间 .isBlock(true)//如果为false 当缓存过期时将会新开线程去更新 当前线程返回老数据 .queueLength(10)//最大缓存数 .build(); User result = mapCache.find("aaa","bbb").getResult(()->new User()); //对象引用缓存 RefCacherefCache=new RefCache(new User(),10,TimeUnit.SECONDS); User user = refCache.get(()->new User()); } } ``` - 对象包装容器 lxs.swift.collector.DictTree ```java import lxs.swift.collector.wrap.Either; import lxs.swift.collector.wrap.Option; import lxs.swift.collector.wrap.Trouble; import java.util.List; class Demo { public static void main(String[] args) { { Option foo = Option.some("foo"); String unwrap = foo.unwrap(); foo = Option.none(); String npe = foo.except("NPE");//throw NPE } { Trouble foo = Trouble.ok("foo"); String unwrap = foo.unwrap(); foo = Trouble.err(new RuntimeException("ERR")); String npe = foo.except("error");//throw error ERR } { Either foo = Either.left("foo"); String unwrap = foo.unwrapLeft(); foo = Either.right(10); String npe = foo.expectLeft("error");//throw error } } } ``` ### 工具类 - http工具类 lxs.swift.tool.http.* ```java import lxs.swift.tool.http.*; import java.nio.charset.Charset; class Demo{ public static void main(String[] args){ Sender sender = Sender.config(Config.of("http://example.com/") .connectTimeout(500) .header("Host","example.com") .param("foo","xxx") .setCharset(Charset.defaultCharset()) ); { //get请求 Getter getter = sender.get(); Receiver receiver = getter.read(); receiver.content(); //receiver.bytes(); } { //post发送json object请求体 JsonPoster jsonPoster = sender.json(); jsonPoster.send("foo","xxx"); Receiver receiver = jsonPoster.read(); receiver.content(); //receiver.bytes(); } } } ``` - 函数式统计工具类 lxs.swift.tool.acc.Accrue ```java import lxs.swift.tool.acc.*; import lxs.swift.tool.acc.Accrue; import java.util.ArrayList; import java.util.HashSet; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; class Demo{ public static class User { String name; long age; boolean isMale; public User(String name, long age, boolean isMale) { this.name = name; this.age = age; this.isMale = isMale; } public String name() { return name; } public long age() { return age; } public boolean isMale() { return isMale; } @Override public String toString() { return "User{" + "name='" + name + '\'' + ", age=" + age + ", isMale=" + isMale + '}'; } } public static void main(String[] args) { Inlet userInlet = new Inlet<>(); Port maxAge = Port.bind(Acc.Int.max(User::age)); userInlet.server(maxAge, (val) -> System.out.println("最大年龄:" + val)); Port> names = Port.bind(Acc.collect(new ArrayList<>(), User::name)); userInlet.server(names, (val) -> System.out.println("全部人的名字:" + val)); Port isMale = Port.bind(Acc.count(User::isMale)); userInlet.server(isMale, (val) -> System.out.println("男生人数:" + val)); Port ageSum = Port.bind(Acc.Int.sum(User::age)); userInlet.server(ageSum, (val) -> System.out.println("总年龄:" + val)); Port minAgeUser = Port.bind(Acc.refreshLazy(Function.identity(), (in, state) -> in.age < state.age ? in : state, Function.identity())); userInlet.server(minAgeUser, (val) -> System.out.println("年纪最小的人是:" + val)); Port total = Port.bind(Acc.count((user)->true)); Port sync = total.sync();//转为线程安全的累加器 userInlet.server(sync, (val) -> System.out.println("总人数:" + val)); userInlet.in(new User("foo", 18, true)); userInlet.in(new User("bar", 19, false)); userInlet.in(new User("foo1", 81, true)); userInlet.in(new User("bar1", 5, false)); userInlet.in(new User("foo2", 12, true)); userInlet.in(new User("bar2", 19, false)); userInlet.notice(); // 最大年龄:81 // 全部人的名字:[foo, bar, foo1, bar1, foo2, bar2] // 男生人数:3 // 总年龄:154 // 年纪最小的人是:User{name='bar1', age=5, isMale=false} // 总人数:6 } } ``` - 排序工具类 lxs.swift.tool.Sorter ```java import lxs.swift.tool.Sorter; class Demo { public static void main(String[] args) { Sorter userSorter = Sorter.create(User::age, User::name, User::isMale); // Sorter.Rank rank = userSorter.rank("age:desc", "name:asc"); Sorter.Rank rank = userSorter.rank(Sorter.desc(User::age), User::name); List users = users(); rank.sort(users); } } ``` - 函数式Try lxs.swift.operation.Try ```java import lxs.swift.operation.Try; class Demo { public static void main(String[] args) { Try.runOf(() -> System.out.println(5 / 0)) .then(() -> System.out.println(5)) .caught(System.out::println) .finalize(()-> System.out.println("finalize...")) .run(); String aaa = Try.valueOf(() -> 5 / 2) .then(Object::toString) .caught(Throwable::toString) .finalize(()-> System.out.println("finalize...")) .ret(); System.out.println(aaa); } } ``` - 模式匹配 Match lxs.swift.operation.match.Match ```java class Demo { public static void main(String[] args) { { Option some = Option.some(5); Integer i = some.match(v -> v / 5, () -> 7); System.out.println(i); } { Trouble ok = Trouble.ok(5); String s = ok.match(v -> v + "ok", v -> v + "err"); System.out.println(s); } { Either left = Either.left("5"); left.match(System.out::println, v -> { System.out.println(v); }); } String s = Match.from(1).of( $if(v -> v == 5, "555"), $eq(1, "1"), $eq(2, "2"), $eq(3, "3"), $type(Integer.class, "class"), $eq(6, (v) -> v + "1"), $("9") ); System.out.println(s);//"1" } } ``` ### 验证器 lxs.swift.verify.Tester ```java import lxs.swift.verify.Tester; import lxs.swift.verify.getters.Get; import lxs.swift.verify.getters.IntGet; import lxs.swift.verify.getters.StrGet; public class Demo { public static class User { String name; long age; boolean isMale; public User(String name, long age, boolean isMale) { this.name = name; this.age = age; this.isMale = isMale; } public String name() { return name; } public long age() { return age; } public boolean isMale() { return isMale; } } public static void main(String[] args) { Tester tester = new Tester<>(RuntimeException::new); IntGet age = Get.ofInt(User::age); StrGet name = Get.ofStr(User::name); tester.unexpected(age.isNull(), "年龄不能为空"); tester.unexpected(age.between(0, 18), "年龄区间不能在[0,18],age={age}"); tester.execOnExcepted(name.isEmpty(), (user) -> user.name = "foo"); tester.expected(name.matches("foo.*"), "名称必须以foo开头,name={name}"); tester.test(new User("foo", 18, true)); } } ```